Problem with fetch http PATCH request with /:id suffix. With DELETE it works perfectly

Issue

I have problem with correctly fetch http with trip._id suffix. Everything works perfectly with DELETE method. But when I am trying use PATCH on it then I get http://localhost:4000/api/tracks/undefined 404 (Not Found). Outside the function console.log(trip._id) is showing correct parameters. Any idea how to get to this PATCH method?

const handleDeleteClick = async () => {
  const response = await fetch("http://localhost:4000/api/tracks/" + trip._id, {
    method: "DELETE"
  })

  const json = await response.json()

  if(response.ok){
      dispatch({type: "DELETE_TRIP", payload: json})
  }
}

const handleUpdateSubmit = async (e) => {
  e.preventDefault()
  const trip = {dateStop}
  
  const response = await fetch("http://localhost:4000/api/tracks/" + trip._id, {
    method: "PATCH",
      body: JSON.stringify(trip),
      headers: {
          "content-type": "application/json"
      }
  })
    const json = await response.json()

  if(!response.ok) {
    setError(json.error)
    console.log(trip)
  }
  if(response.ok) {
    setError(null)
    setParagraphClicked(false)
    dispatch({type: "CREATE_TRIP", payload: json})
  }
}

Code from route control:

const updateTrack = async (req,res) => {
const { id } = req.params
if(!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(404).json({err: "Can't patch this trip"})
}
const trip = await Trip.findOneAndUpdate({_id:id}, {...req.body})

 if(!trip) {
    return res.status(404).json({error: "No such trip tracked"})
} else {
   return res.status(200).json(trip)
}

}

//UPDATE specific track

const router = express.Router()
router.patch("/:id", updateTrack)

Solution

You are creating an object named trip in handleUpdateSubmit function by assigning it value { dateStop } this will create a trip object with dateStop key in it and _id will be undefined because it doesn’t exits in this trip object.

Answered By – Muhammad Usama

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published