1
    const [rowData, setRowData] = useState([]);
    const old = {id: 'stud1', name: 'jake', room: '2'};
    const newData = {name: 'jake', room: '3A'};

    useEffect(() => {
        let ignore = false;
        (async function getUsers() {
          let response = await getAll({ length: 999 });
          if (!ignore) setRowData(response['data']['data']);
        })()
        return () => {
          ignore = true;
        }
      }, []);

    (async function updateItem() {
              await update(oldData.id, newData).then(response => {
//value of response['data'] = {id: 'stud1', name: 'jake', room: '3A'}
                setRowData(arr => [...arr, response['data']]);
              }).catch(err => {
                console.log(err);
              })
            })()

How to update the array list without appending a new data. cause I tried this setRowData(arr => [...arr, response['data']]); then it keeps appending a data.

Instead it will update the value in the array it will append on it.

1
  • what does rowData array contain and what is response['data']; Commented Mar 12, 2021 at 5:13

2 Answers 2

1

Since you want to update one item within the state array, you can use map and update the item based on the id like below

  (async function updateItem() {
      await update(oldData.id, newData).then(response => {
        setRowData(arr => arr.map(item => {
                if (item.id === response.data.id) {
                     return response.data;
                }
                return item;
         });
      }).catch(err => {
        console.log(err);
      })
    })()
Sign up to request clarification or add additional context in comments.

2 Comments

I try to update the data. then all the data on the array are similar
@BeginnerCoder I did not understand what you meant to say. Are you saying that all the content within the array update with the new object?
1

I do not think you need a spread operator.. you can just use array.map().. maybe something like this will help you..

const old = [{id: 'stud1', name: 'jake', room: '2'},{id: 'stud2', name: 'jack', room: '2'}];
const newData = {id: 'stud1', name: 'jakey', room: '3A'};

const x = old.map((stud) => {
  if(stud.id === newData.id){
    stud = newData;
  }
  return stud;
});
console.log(x);

then you can use the x for setRowData(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.