I have an array with length === 4 Please note that the length may vary based on some outside parameters. I want to run a function that generates input fields according to the length of my array onComponentDidMount using useEffect.
const [blankField, setBlankField] = useState([dynamicFields]); // This adds the input fields with the required data
const legs = [{...}, {...}, {...}, {...}]; // the length of legs[] may vary in number
const addField = () => {
setBlankField([...blankField, [...dynamicFields]]);
};
useEffect(() => {
if (legs) {
legs.map(leg => {
console.log(leg);
return addField();
});
}
}, []);
blankFields.map(......);
I want it to generate as many fields as the length of the array immediately the component mounts.
If you give
[]asdependency of useEffect, it only runs once when the component is mounted. Instead write it as,Now, it will trigger for every change in
length