0

I am trying to use context API object in my component and update the same context object twice (once during initial component load and other on cell click)

For some reason, when I update it on cell click and console out the value, it still has the earlier value i.e. the earlier value set during load. Why is this?

My expectation is that context object should get overwritten entirely on cell click with the new values.

Below is my relevant code;

const [data, setData] = React.useContext(DataContext);

useEffect(() => {
        if (props.someThing) {
            setData({
                attr1: '1',
                attr2: '2'
            })
        }
    
}, [data.attr1]);

const onCellClick = (e) => {
    console.log(e);
    if (data.attr1 === '1') {
        setData({
            newAttrPostClick1: '3',
            newAttrPostClick4: '4'
        });
        console.log("data : " + JSON.stringify(data)); // This is printing {attr1: '1',attr2: '2'} and not {newAttrPostClick1: '3',newAttrPostClick4: '4'}
        history.push("/SomePage");
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • Note that we prefer a technical style of writing here. We gently discourage greetings, hope-you-can-helps, thanks, advance thanks, notes of appreciation, regards, kind regards, signatures, please-can-you-helps, chatty material and abbreviated txtspk, pleading, how long you've been stuck, voting advice, meta commentary, etc. Just explain your problem, and show what you've tried, what you expected, and what actually happened. – halfer Aug 13 '21 at 21:51

1 Answers1

0

That's completely normal, you can't expect the console.log immediately done after the setData to have the latest value, React dispatch values in an async manner for performance reasons, if you still want to be sure you have the latest value you want, either display it inside your component or use useEffect to console it, and it will console the latest value

Louay Al-osh
  • 3,177
  • 15
  • 28