How to remove a single object from Array Properties in React Js?

I have a state like:

const initialFieldValue={
...............

photos:[]
.........

}

const [state, setState] = useState(initialFieldValue);

Then I was pushing some object one by one through onClick function like that:

const handlePush=()=>{
     state.photos.push({
        fieldId: Math.random(), 
        file: file , /// from upload file
      });
    }
}

Now I want to remove those object one by one onClick function like

const handleRemove=(fieldId )=>{
    const tableDoc = [...state.photos];
    tableDoc.splice(
      tableDoc.findIndex(value => value.fieldId === fieldId),
      1,
    );
    state.photos = tableDoc;
}

Answer

Solution:

Change this line

state.photos = tableDoc;

to

setState({...state, photos: tableDoc});

Refactor code:

const newPhotos = state.photos.filter(value => value.fieldId !== fieldId);
setState(prevState => ({...prevState, photos: ...newPhotos }));

Note:

  1. Don’t mutate data in React Js: The same as handleRemove method, you shouldn’t mutate data directly, please do something like this in handlePush
const newPhoto = {fieldId: Math.random(),file: file};
setState(prevState => ({...prevState, photos: [...prevState.photos, newPhoto]}));
  1. Keep in mind that, from reactjs.org docs say that:

Unlike the setState() method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});