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

Time:08-24

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)

CodePudding user response:

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.

  • Related