score:3

Accepted 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};
});

score:0

Thanks Everyone for trying to solution for me . Everyone is right. but I can modification like that:

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

//New

handleChange =()=>{
setState({
      ...state,
      photos: [...state.photos, { 
        fieldId: Math.random(), 
        file: file , /// from upload file 
      }],
    });
}




then Remove function:

//old
const handleRemove=(fieldId )=>{
    const tableDoc = [...state.photos];
    tableDoc.splice(
      tableDoc.findIndex(value => value.fieldId === fieldId),
      1,
    );
    state.photos = tableDoc;
}
//New
  const handlePhotoRemove = fieldId => {
    const tabPhotos = [...state.photos];
    tabPhotos.splice(
      tabPhotos.findIndex(value => value.fieldId === fieldId ),
      1,
    );
    setState({
      ...state,
      photos: tabPhotos,
    });
  };

It is successfully done!!

thanks. Plz tell me if have any easy solutions

score:1

In addition to the above solution, You can try all in a single line (no need to spread, findIndex, and splice)

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

Related Query

More Query from same tag