I’m having an issue getting my setState() ‘setSections(data.sections)’ to work. I’m trying to save data locally and is successful, as on reload the loaded data from the previous session is shown in the returned JSON.
const CVEditor = () => {
const [sections, setSections] = useState([]);
// Load data from local storage when the component mounts
useEffect(() => {
const data = loadData();
console.log("Loaded data from local storage:", data); // Debugging line
if (data.sections && Array.isArray(data.sections)) {
console.log("Setting sections:", data.sections); // Debugging line
setSections(data.sections);
console.log(sections);
} else {
console.warn(
"Loaded sections data is not an array or undefined:",
data.sections
);
}
}, []);
I’ve checked all the logs and my data.sections is returned as follows
[
{
"title": "asdasd",
"content": "asdasd",
"id": 1720033119342
}
]
I can’t see anything wrong with the array or any data discrepancies. Imports are all correct aswell. I am wondering why, when I call setSections(data.sections); the state of sections is still an empty array. The state of ‘sections’ is updated successfully in my addSection function later in the class
const addSection = () => {
const newSection = { title: "", content: "", id: Date.now() };
console.log("Adding section:", newSection); // Debugging line
setSections((prevSections) => {
const updatedSections = [...prevSections, newSection];
console.log("Updated sections:", updatedSections); // Debugging line
return updatedSections;
});
};
Thanks in advance
Expected the state of Sections to be updated, however nothing was changed
James Cooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.