This is the current value of the state (myState):
[{“id”: 123, “title”: “book 1”}]
When a user tries to add a new book, I want to check if the Id matches any of the ids which are already in the state variable. I tried doing this:
if (!myState.map(a => a.id).includes(newBook.id)) setMyState([newBook, ...myState]);
This works fine but I don’t think it is the correct approach because the state update is asynchronous so the user might be able to add the same book twice if the state is not updated fast enough. What is the best pattern for these situations?
Aucun commentaire:
Enregistrer un commentaire