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

Nadav Yair
  • 73
  • 10

0 Answers0