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.