0

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 enter image description here

enter image description here

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.

link to sandbox

  • 1
    `{ ...EMPTY_OBJECT }` makes a shallow copy of your template object, so the nested `children` array remains the same array for both objects, and the object nested in the array is yet another level. I've linked a duplicate re: deep cloning, but actually I think you might want to revisit your whole approach. – pilchard Dec 09 '22 at 16:40
  • Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – pilchard Dec 09 '22 at 16:41

0 Answers0