psudo
psudo

Reputation: 1568

Updating state in react js shallow copy or what

I have the following state in my app:

  const [work, setWork] = useState([
    {
      company: "Company",
      position: "President",
      website: "example.com",
      startDate: "2013-01-01",
      endDate: "2014-01-01",
      summary: "Description...",
      highlights: ["Started the company", ""],
      field1: false,
      field2: false,
    },
  ]);

And the following method to update the state [push a copy of object into the array]:

  const addNewField = () => {
    let newField = [...work];
    let a = {...work};
    newField.push(a);
    setWork(newField);
    console.log(work);
  };

I have also tried immutable way to update the state;

  const addNewField = () => {
    let newField = {...work};
    setWork((prev) => ([
      ...prev,
      newField
    ]));
  }

With both of the above code to update the state I'm getting an error of:

Cannot read property 'map' of undefined

Pointing to the line where I map objects to input fields.

But when I do the following method

  const addNewField = () => {
    let newField = [...work];
    let a = {...work};
    newField.push(    {
      company: "Company",
      position: "President",
      website: "example.com",
      startDate: "2013-01-01",
      endDate: "2014-01-01",
      summary: "Description...",
      highlights: ["Started the company", ""],
      field1: false,
      field2: false,
    });
    setWork(newField);
    console.log(work);
  };

There is no error and I'm able to add new field on click action. I cannot figure out the cause of error in the first 2 codes. Is this the cause of shallow copy ? How do I overcome it ? Even it works I don't want to push hardcode object into array.

Upvotes: 0

Views: 356

Answers (1)

psudo
psudo

Reputation: 1568

The final working code:

  const addNewField = () => {
    // let newField = [...work];
    // let a = {...work[0]};
    // newField.push(a);
    // setWork(newField);
    
    // OR
    
    setWork((prev) =>[
      ...prev,
      prev[0]
    ]);
  };

Thanks to @Chris G for suggestion

Upvotes: 1

Related Questions