Search code examples
javascriptreactjsappwrite

Updating an item within an array and maintain its index


I'm trying to update my state with new information that is passed through response.payload. This is my current code:

if(response.events.includes('databases.*.collections.*.documents.*.update')) {
 setMemos(prevState => prevState.filter(memo => memo.$id !== response.payload.$id))
 setMemos(prevState => [response.payload, ...prevState])
}

It does technically update the information which is what I wanted it to do however, it causes the item to lose its index. I want to simply update the specific "memo" that the payload is referring to and have it keep its index.

That was quite hard to explain so if you don't understand what I'm on about, just let me know and I'll try and explain further.


Solution

  • You can try creating a copy and updating that by index and finally returning that like the following way:

    if(response.events.includes('databases.*.collections.*.documents.*.update')) {
      setMemos(prevState => {
         //create a copy of the previus state
         const updatedMemo = [...prevState];
         //find the index of the memo that marches the $id
         const memoIdx = updatedMemo.findIndex(memo => memo.$id === response.payload.$id);
         //if found update in that specific index
         if(memoIdx !== -1){
           updatedMemo[memoIdx] = response.payload;
         }
         return updatedMemo;
       });
    }