1

I've been doing my latest code with redux tool kit . I've created a simple contact form that fetches data from the rest api(Via JSON placeholder). And also allows a user to add a contact and also edit a contact. However, when it comes to deleting a contact, I've run into a bit of a problem. Despite grabbing the user by its ID, I'm still unable to remove the contact from the page. If possible, could anyone tell me what I'm doing wrong? Thanks.

I've provided a screenshot of the reducer, the dispatch, and the results in the console via logger.

Reducer

createAsyncThunk

Dispatch

Console log via logger

1 Answers1

0

The problem is in your reducer. The action in your deleteContacts.fulfilled case reducer is not what you are expecting it to be.

You are currently looking for the id of the deleted contact on the action.payload.id property. This is incorrect. The action.payload of a fulfilled thunk action will contain the JSON data that was returned from the server. In your case it looks like that response is empty and does not contain the id of the deleted user.

Instead you can access the id by looking at the argument which was used to call the thunk. This value is stored in the action.meta.arg property.

state.contacts = state.contacts.filter(
  (contact) => contact.id !== action.meta.arg
);

Related docs: Promise Lifecycle Actions


FYI the object syntax of extraReducers which you are using here is now deprecated. You'll want to switch to the builder callback syntax.

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
  • Ah ok. I'm still relatively new to redux-tool kit. So this well helpful. But with the said, thank you, that worked! :) and thank you for letting me letting me know about the builder callback syntax as well! – classic88design Oct 06 '22 at 19:44