iorabiadopo
iorabiadopo

Reputation: 5

useEffect setData not setting data despite values being new

so this is the piece of code

const handleChange = (e, tipo) => {
    console.log(e.target.value);   //0
    console.log(data[tipo]);   //1
    data[tipo] = e.target.value;
    console.log(data[tipo]);    //2
    console.log(data);    //3
    setData(data);
  };

Console.log 2 and 3 tell me that that the manipulated data changed, showing me the char that I inserted, but when I do the setData it does not even fire up the useEffect!

 useEffect(() => {
    console.log("____________________________________");
    console.log(data);
    console.log("____________________________________");
  }, [data]);

It prints it only once while the data is being requested.

Upvotes: 0

Views: 2324

Answers (1)

MohammadAmin Mohammadi
MohammadAmin Mohammadi

Reputation: 1211

After you made chages to data, set data as follow:

If data is an array:

setDate([...data]);

And this if data is an object:

setDate({...data});

React will track ref of data not changes you made inside data so if you want your changes to take affect consider pass a new ref to setData().

Upvotes: 1

Related Questions