Home > database >  React SetState Array with function
React SetState Array with function

Time:01-31

I have an array I wish to keep track of,

const [myArray, setMyArray] = useState([]);

I want this to be an array of MyCustomObject

I am then creating the array in my useEffect():

const newObject = new MyCustomObject(); //initiate object and set values (removed to simplify)

setMyArray(newObject);

I want to override myArray rather than push onto the list. How do I do this?

CodePudding user response:

I assume that you have array of object and want to override one object of it with new one

you can do it by using prevState and findIndex

like this:

  const [myArray, setMyArray] = useState([]);
  const newObject = new MyCustomObject();

  setMyArray((prevState)=>{
    let newArr = prevState;
    if(newArr.length === 0 ){
      return [newObject]
    }
    let arrIndex = newArr.findIndex(item => item.id === newObject.id)
    if(arrIndex !== -1){
      newArr[arrIndex] = newObject
    }
    return newArr
  });

CodePudding user response:

You should use the spread operator.

Try this

setMyArray([...newObject]);

Hope this helps

CodePudding user response:

You want the state to be an array of an object, so set the state likewise.

Solution

setMyArray([...myArray, newObject])

This should work smoothly.

  • Related