1

I was trying to delete data/object from my database with fetch delete request method, using React hooks and Redux.

I got stuck and I couldn’t find an answer for my question.

Eventually some how I came across a solution,

Using the question enter link description here

and converting the solution that will fit React Hooks and Redux, I used "useDispatch" instead "mapDispatchToProps"

First you need to import "useDispatch" from react-redux, and your Delete function from actions

import { deleteSet } from './Actions'
import { connect ,useDispatch} from 'react-redux';

Then you can declare dispatch inside your functional component

const dispatch = useDispatch();

The method to call

// take the id of the itme/object you want to delete
const deleteItem = (item) => {
    const itemId = item._id
    console.log(itemId);
// use the dispatch you declared earlier with the function you import from Actions
    dispatch(deleteSet(itemId));
};

The Delete function from "Actions"

export const deleteSet = (id) => (dispatch) =>  {
    fetch(`/api/orders/${id}`, {
      method: "DELETE",
    })
    .then(response => response)
    .then(id => dispatch(
      {
        type: DELETE_ITEM,
        payload: deleteSet(id)
       }
      ))  
    }

This is the reducer

switch (action.type) {
        case DELETE_ITEM:
            return {item: action.payload};
        default:
           return state
    };

This is the server.js I use for this delete function

app.delete("/api/orders/:id", async (req, res) => {
    const order = await Order.findByIdAndDelete(req.params.id);
    res.send(order)
})


I hope that this will help you in your journey

If someone have improvements to this post Definitely post it below Thank you and have fun coding 😊🤟

2
  • What's the question? What result do you expect? Commented Dec 3, 2021 at 2:07
  • you miss understood I solved it already. but because I couldn’t find an answer here I wrote my answer that i came up with Commented Dec 3, 2021 at 10:06

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.