-3

am having a problem understanding react state . i am pushing an object on click of a button taking multiple values from input fields into array . onClick of button should show the latest state but its showing the previous input values from the form. how could i resolve this issue .

let addToList = ()=>{

let data={};

data.component=returnCmpName(SelCom);

data.question=question;

switch(SelCom){

case 1 : case 2:

data.required=checked;

data.errorMessage=errorMessage;

break;

case 3 : case 4 : case 5: data.options=NewList.slice(); break;

case 6:

data.fileAllowed=fileAllowed;

data.fileLimit=fileLimit;

break;

case 7: break;

case 8: break;

default:break;

}

rendcompState(prevData=>[data,...prevData])

console.log(rendComp)

}
  • React state updates are asynchronously processed, so attempting to console log it right after enqueueing an update will only ever log the state value from the current render cycle, not what it will be updated to on a subsequent render cycle. – Drew Reese Oct 11 '21 at 06:37

1 Answers1

0

The code you posted is a bit vague,
but it seems like you are trying to log the state right after setting it.
Setting a state in React is an asynchronous action, meaning that it runs in the background while you're code block continues.

This essentially means that when you are trying to log it, the state has still not finished setting.

What you can do instead, is use React's built-in useEffect hook,
which can take an array of dependencies and run a callback function once any of those dependencies have changed in value.

Should look like this:

useEffect(() => {
   console.log(state);
}, [state]);

You simply add this hook in your function component,
and the console.log will only run once the state actually finished updating.

tomleb
  • 2,409
  • 2
  • 9
  • 24