Elcid_91
Elcid_91

Reputation: 1681

Javascript / ReactJS Objects not copying as expected

Given the following code:

I am expecting staticData not to change when gridData does.

import { useState } from "react";
import "./styles.css";

const CheckData = (props) => {
  return (
    <>
      <h1>Data From {props.ds}</h1>
      {props.items.map((row) => (
        <div key={row.recordid}>{row.companyname}</div>
      ))}
    </>
  );
};

export default function App() {
  const [gridData, setGridData] = useState([
    {recordid: 1,companyname: "Devshare"},
    {recordid: 2,companyname: "Shufflebeat"},
    {recordid: 3,companyname: "Mita"}
  ]);

  const staticData = [...gridData];

  const changeValue = () => {
    let nd = gridData;
    nd[2]["companyname"] = "Superman";
    setGridData([...nd]);
  };

  return (
    <div className="App">
      <CheckData ds="gridData" items={gridData} />
      <CheckData ds="staticData" items={staticData} />
      <button style={{ marginTop: "50px" }} onClick={changeValue}>
        Change a value in gridData
      </button>
    </div>
  );
}

Why does value in staticData change when gridData does? I thought I made a copy of the object - not create an instance.

Code SandBox Test Code Here

Upvotes: 0

Views: 35

Answers (1)

David
David

Reputation: 218887

Based on a comment on the question:

staticData is suppose to be a "history" table allowing users to undo things.

Then you're building it in the wrong place. When you do this in the component:

const staticData = [...gridData];

Then on every render you re-build staticData based on the current values in gridData. So when the gridData state is updated and the component re-renders, you build a new staticData with the new values.

If staticData is supposed to be unchanging hard-coded data, define it outside the component:

const staticData = [
  {recordid: 1,companyname: "Devshare"},
  {recordid: 2,companyname: "Shufflebeat"},
  {recordid: 3,companyname: "Mita"}
];

And then within the component use it as the initial state value for gridData:

export default function App() {
  const [gridData, setGridData] = useState(staticData);

  //...
};

That way staticData is only defined once in the module. gridData can be updated in state as many times as you like but that won't affect staticData.

Upvotes: 1

Related Questions