Home > database >  MERN delete data undefined at backend
MERN delete data undefined at backend

Time:04-11

I am trying to implement a delete functionality in my MERN App, but whenever I try to send my delete IDs to backend controller the Delete ID Array is Undefined

deletePosts is an array of IDs to delete deletePosts = [id1, id2, id3 ...]

React Posts Component:-

function AllPosts() {
  const dispatch = useDispatch();

  
  const { posts, isSuccess } = useSelector((state) => state.posts);

  
  const handleDelete = () => {
    dispatch(deletePost({deletePosts}));
  };

  return (
                <>
                      {posts.map((post, index) => (
                        <Post
                          postId={post._id}
                          subject={post.subject}
                          handleDelete={handleDelete}
                        />
                      ))}
                
                </>
    
  )}

export default AllPosts;

Redux Toolkit Slice:-

export const deletePost = createAsyncThunk(
    "posts/delete",
    async (postDelete, thunkAPI) => {
      try {
        
        const token = JSON.parse(localStorage.getItem("token"));
    
        return await postService.deletePost(postDelete, token);
    
    } catch (error) {
        const message =
          (error.response &&
            error.response.data &&
            error.response.data.message) ||
          error.message ||
          error.toString();
  
        return thunkAPI.rejectWithValue(message);
      }
    }
  );

REDUX Toolkit Service:-

const deletePost = async (postDelete, token) => {
    const config = {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    };
  
    
    const response = await axios.delete(API_URL, postDelete, config);
        
    return response.data;
  
};

ROUTE:-

router.route("/").delete(protect, deletePost)

CONTROLLER:-


const deletePost = asyncHandler(async (req, res) => {
    console.log("Delete Controller:-  ", req.body);

    /****
     * 
     *    Delete Logic 
     * 
     * 
     */
  
  });

CONTROLLER console.log:-

Delete Controller:-  {}

Data is passed from Component > Slice > Service > Route > Controller

the deletePosts array has content of Ids till REDUX toolkit Service but in the controller is shows Undefined

CodePudding user response:

Maybe this will solve your problem:

const deletePost = async (postDelete, token) => {
    const config = {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      data:{
          postDelete 
      }
    };  
    const response = await axios.delete(API_URL, config);      
    return response.data;
};

Also you are sending your deleted as an object, if this is not intended please change the following in your react posts component

const handleDelete = () => {
  dispatch(deletePost(deletePosts)); // ({deletePosts}) will give you an object of deleted posts in the destination instead of an array

};
  • Related