0

Here are 2 functions in my React Context:

 const addComponent = (component) => {
    console.log("adding component to readable template");
    setReadableTemplate([...readableTemplate, component]);
  };

  const updateTemplate = (component) => {
    const index = readableTemplate.findIndex((obj) => obj.id == component.id); // gets the index position of the component
    const updatedComponent = Object.assign({}, readableTemplate[index]); // copys component
    updatedComponent.props = component.props; // updates the props property of the component
    const newReadableTemplate = readableTemplate.slice(); // copys the readable template array
    newReadableTemplate[index] = updatedComponent; // updates new readable template array with the updated component
    setReadableTemplate(newReadableTemplate);
    console.log(readableTemplate); // Value is not being updated -- It's printing out old value
  };

In the updateTemplate function, console.log after setState is printing old value and not the new one. Not sure how to fix this. Any idea how to fix it?

Note: the value is same even after updateTemplate function ran multiple times. So I am not sure if async has anything do with this.

Sumanth Jois
  • 3,146
  • 4
  • 27
  • 42
  • State updates in React is done asynchronously. – Terry Apr 06 '23 at 06:56
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Terry Apr 06 '23 at 06:57
  • The value is same even after the update function reruns for 3rd and 4th time -- the time gap between each rerun is over a minute.. I would think the value would atleast get updated then but it isn't getting updated at all. – Sumanth Jois Apr 06 '23 at 07:00
  • Does this answer your question? [React, state not getting updated when calling the related setState](https://stackoverflow.com/questions/71004802/react-state-not-getting-updated-when-calling-the-related-setstate) – Youssouf Oumar Apr 06 '23 at 08:13

0 Answers0