Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I use fetch my .then code isn't working

So I am trying to redirect after I am deleting the page, it get’s deleted from the database but it doesn’t redirect me to my homepage. It worked fine when I was using json-server locally, but when I started using Mongoose it wasn’t working properly and wasn’t redirecting.

The code inside .then isn’t working, I tried console.log inside the .then but it didn’t log

I am using mongoose as my database

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my entire component:

import { useParams } from "react-router-dom";
import useFetch from "../useFetch";
import { useHistory } from "react-router-dom";
import moment from "moment";

import profile_image from "../images/picture.jpg";

const BlogDetails = () => {

    let blogDate = moment().format('D MMM YYYY');
    const { id } = useParams();
    const { data: blog, isPending, errorMsg } = useFetch("http://localhost:5000/postsdata/" + id);
    const history = useHistory()

    const handleDelete = () => {
        fetch('http://localhost:5000/postsdata/' + blog._id, { method: 'DELETE' })
            .then(() => {
                history.push('/');
            })
            .catch((err) => console.log(err))
    }

  return (
    <div className="blog-details">
      <div className="top-profile">
        <div className="top-profile-picture">
          <img src={profile_image} alt="profile-pic-top" />
        </div>
        <div className="top-profile-name">
          <p>Vishwajeet Deshmukh</p>
        </div>
      </div>
      {isPending && <div>Loading...</div>}
      {errorMsg && <div>{errorMsg}</div>}
          {blog && (
        <article className="blog-main-content" >
          <div className="main-content-header">
            <div className="content-title-date">
              <h2 className="blogdetails-title">{blog.title}</h2>
              <p className="blogdetails-date">{blogDate}</p>
            </div>
            <div className="content-image">
                <img src={blog.imgsrc} alt="" />
            </div>
          </div>

          <div className="blogdetails-body"><p>{`${blog.postBody}`}</p></div>
          <button className="blogdetails-delete" onClick={handleDelete}>Delete Me</button>
        </article>
      )}
    </div>
  );
};

export default BlogDetails;

Here is my router.js which handles my delete

const express = require('express');
const router = express.Router();
const { Posts } = require("./models");

//<----------------------------------- CRUD OPERATIONS ------------------------------------------>

router.get("/", () => {
    console.log("Server Connected");
})

//<---------------------------- Get Posts from Database ---------------------------->

router.get("/postsdata", (req, res) => {
    
    Posts.find((err, data) => {
        if (err) {
            res.status(500).send(err);
        } else {
            res.status(201).send(data);
        }
        return null;
    })
})

//<------------- Get Specific Posts from Database --------------->

router.get("/postsdata/:_id", (req, res) => {
    const id = req.params._id;
        Posts.findById(id, (err, data) => {
            if (err) {
                res.status(500).send(err);
                throw new Error(err)
            } else {
                res.status(201).send(data);
            }
            return data;
        })
})

//<---------------------------- Post On the Posts Database ---------------------------->
router.post("/postsdata", (req, res) => {
    
    const db = req.body;
    Posts.create(db, err => {
        if (!err) {
            console.log("Posted on Server");
        } else {
            throw new Error(err)
        }
        return null
    })
})

//<---------------------------- Delete Posts from Database ---------------------------->
router.delete("/postsdata/:id", (req, res) => {
    const id = req.params._id
    Posts.deleteOne(id, (err, data) => {
        if (err) {
            console.log(err);
            throw new Error(err)
        } else {
            console.log(data);
        }
        return null
    })
})

module.exports = router;

>Solution :

after deleting the postdata, send a response from the API.


    router.delete("/postsdata/:id", (req, res) => {
    const id = req.params._id

    Posts.deleteOne(id, (err, data) => {
        if (err) {
            console.log(err);
            throw new Error(err)
        } else {
            return res.status(200).json({status: 'success'}); // try with this
        }
        return null
    })
    })

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading