skip to Main Content

I have a useState in nextjs that has values like this:

const [sampleData, setSampleData] = useState({
     value1: ''
     value2: ''
     value3: []
   });

If I want to update the state of value1 for instance while keeping the rest of the state, I would do something like this:

setSampleData({...sampleData, value1: 'new value'});

This works. However, if I want to update the state of value3 which is an array and still keep the previous array contents it has before, how do I achieve this?
Doing something like this would replace the entire state of value3 array with the new set of arrays:

 setSampleData({...sampleData, value3: [new array]});

Is it possible or should I simply use another format entirely such as useReducer hook?

3

Answers


  1. currecntly you have some options to achieve this,

    Option1:

     setSampleData({...sampleData, value3: [...sampleData.value3, newValue]});
    

    Option2:

    const temp = {...sampleData}
    temp.value3.push(newValue)
    setSampleData({...temp});
    
    Login or Signup to reply.
  2. You can use an inner spread such as:

    setSampleData({
      ...sampleData,
      value3: [...sampleData.value3, 'new value']
    });
    
    Login or Signup to reply.
  3. For adding extra logic to the setter, You can also pass a callback function to the state setter as such (instead of just the new state)

    You can refer the docs to read more about it, but I guess this should work for your case.

    setSampleData((prevSampleData) => {
      const newSampleData = {...prevSampleData};
      newSampleData?.value3.push("New Sample") // add your own logic here
      return newSampleData
    });
    

    The returned value of this callback is what gets set as the new state

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search