Function in useEffect runs once whereas I want to run concurrently

186 views Asked by At

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.

1

There are 1 answers

2
Prakash Reddy Potlapadu On

If you give [] as dependency of useEffect, it only runs once when the component is mounted. Instead write it as,

  useEffect(() => {
    if (legs) {
      legs.map(leg => {
        setCount([count + 1]);
        console.log(count, leg);
        return addField();
       });
    }
  }, [legs.length]);

Now, it will trigger for every change in length