I'm currently trying to parse an init state to multiple components. but parsing the state equals to the same state for all components even thou the logging in the useEffect logs out correctly . There are some array and or object references that JS holds even though I create new copies of objects.
export default function App() {
return (
<div className="App">
<h1>My component</h1>
<MyComponent id={"component-1"} initContent={"component-1-content"} />
<MyComponent id={"component-2"} initContent={"component-2-content"} />
</div>
);
}
The components them self takes in the init content but since the render function is dependent on an array of object I need to parse the content before displaying the value
import { useEffect, useState } from "react";
type OBJECT_TYPE = {
text: string;
children: {
text: string;
}[];
};
const EMPTY_OBJECT: OBJECT_TYPE = {
text: "",
children: [
{
text: ""
}
]
};
export const MyComponent = ({
id,
initContent
}: {
id: string;
initContent: string;
}) => {
const [contentObject, setContent] = useState<[OBJECT_TYPE] | undefined>();
useEffect(() => {
const newContent = { ...EMPTY_OBJECT }; // copy the object
newContent.children[0].text = initContent;
console.log(newContent.children[0].text); // logs out correctly
setContent([newContent]);
}, [initContent]);
if (!contentObject) return null;
return <div>{contentObject[0].children[0].text}</div>; // Wrong render
};
As you can see here, the renders does not output the correct state
I know there is something about JS array reference or something, but given the state in the useEffects logs out the correct content I'm not sure what is happening. I know I can use JSON.parse(json.stringify(newContent))
to make sure there is no lagging reference, but I want to know whats it happening, and how this could be solved more cleanly.