0

I just started coding and I tried to delete a post through my mongoDB API. The code that I used is pretty basic, my API requests all go through a reducer which is set up pretty clear. But when I try to delete a post from my DB, I get the error ''[Unhandled promise rejection: Error: Request failed with status code 404]''. Did I do something wrong here or is this a mongoDB problem? I've included the necessary code.

This is my reducer request:


    const deleteWorkout = (dispatch) => {
  return async (_id) => {
    await trackerApi.delete(`/workouts/${_id}`);
    dispatch({ type: "delete_workout", payload: _id });
  };
};

This is my complete reducer code:

    import createWorkoutDataContext from "./createWorkoutDataContext";
import trackerApi from "../api/tracker";

const workoutReducer = (workouts, action) => {
  switch (action.type) {
    case "get_workouts":
      return action.payload;

    case "add_workout":
      return [
        ...workouts,
        {
          title: action.payload.title,
          exercises: action.payload.exercises,
        },
      ];

    case "edit_workout":
      return workouts.map((Workout) => {
        return Workout._id === action.payload.id ? action.payload : Workout;
      });

    case "delete_workout":
      return workouts.filter((Workout) => Workout._id !== action.payload);

    default:
      return workouts;
  }
};

const getWorkouts = (dispatch) => async () => {
  const response = await trackerApi.get("/workouts");
  dispatch({ type: "get_workouts", payload: response.data });
};

const addWorkout = (dispatch) => {
  return async (title, exercises, callback) => {
    await trackerApi.post("/workouts", { title, exercises });

    if (callback) {
      callback();
    }
  };
};

const editWorkout = (dispatch) => {
  return async (title, exercises, _id, callback) => {
    await trackerApi.put(`/workouts/${_id}`, { title, exercises });

    dispatch({ type: "edit_workout", payload: { _id, title, exercises } });
    if (callback) {
      callback();
    }
  };
};

const deleteWorkout = (dispatch) => {
  return async (_id) => {
    await trackerApi.delete(`/workouts/${_id}`);
    dispatch({ type: "delete_workout", payload: _id });
  };
};

export const { Context, Provider } = createWorkoutDataContext(
  workoutReducer,
  { addWorkout, getWorkouts, deleteWorkout },
  []
);

This is my code where I use the delete function:

    const WorkoutListScreen = () => {
  const { workouts, getWorkouts, deleteWorkout } = useContext(WorkoutContext);

  return (
    <View style={styles.container}>
      <Text style={styles.pageTitle}>My Workouts</Text>

      <NavigationEvents onWillFocus={getWorkouts} />

      <FlatList
        data={workouts}
        keyExtractor={(item) => item._id}
        renderItem={({ item }) => {
          return (
            <TouchableOpacity
              onPress={() => navigate("WorkoutDetail", { _id: item._id })}
            >
              <View style={styles.row}>
                <Text style={styles.title}>{item.title}</Text>

                <TouchableOpacity onPress={() => deleteWorkout(item._id)}>
                  <Ionicons style={styles.deleteIcon} name="trash-outline" />
                </TouchableOpacity>
              </View>
            </TouchableOpacity>
          );
        }}
      />

I simply included the deleteWorkout function in my TouchableOpacity, so I suppose that the problem lies within the reducer code?

here is the error I keep getting:

[Unhandled promise rejection: Error: Request failed with status code 404]
at node_modules\axios\lib\core\createError.js:16:14 in createError
at node_modules\axios\lib\core\settle.js:17:22 in settle
at node_modules\axios\lib\adapters\xhr.js:66:12 in onloadend
at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:614:6 in setReadyState
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:135:10 in EventEmitter#emit
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue

This is what the objects in my databse look like (through Postman):

{
    "userId": "615e06f36ce5e5f1a69c675e",
    "title": "Defaults test",
    "exercises": [
        {
            "exerciseTitle": "shadowboxing",
            "exerciseProps": {
                "time": 0,
                "sets": 0,
                "reps": 0
            },
            "_id": "6184c6fa685291fb44778df7"
        },
        {
            "exerciseTitle": "bag workout",
            "exerciseProps": {
                "time": 4,
                "sets": 0,
                "reps": 12
            },
            "_id": "6184c6fa685291fb44778df8"
        },
        {
            "exerciseTitle": "Exercise",
            "exerciseProps": {
                "time": 4,
                "sets": 3,
                "reps": 12
            },
            "_id": "6184c6fa685291fb44778df9"
        }
    ],
    "_id": "6184c6fa685291fb44778df6",
    "__v": 0
}

I'm gratefull for your help!

  • You are not managing the error in your reducer. Try to set a try/catch and print the error. Should be more readable – Francesco Clementi Nov 04 '21 at 08:45
  • Ooh allright I'll do that this evening, thank you already, hopefully that will give me thr information I need to fix this issue! – Saber Bouazzaoui Nov 04 '21 at 11:07
  • Consider that 404 error usually means that the api you are calling doesn't exist, so it could be that your error will not be more readable – Francesco Clementi Nov 04 '21 at 11:09
  • When I catch the error message, I still get the same error. It's still error 404. I think the refference is right, I really don't know what the problem is, but if it's an error 404 it meaéns that it can't find the object I am looking for, so it means that it has to be my refference to the object's id that isn't right? – Saber Bouazzaoui Nov 05 '21 at 05:12
  • This is how I changed my code to ctahc the error: ´const deleteWorkout = (dispatch) => { return async (_id) => { try { await trackerApi.delete(`/workouts/${_id}`); dispatch({ type: "delete_workout", payload: _id }); } catch (err) { dispatch({ type: "add_error", payload: err }); console.log(err); } }; };´ – Saber Bouazzaoui Nov 05 '21 at 05:12
  • Do you have the same error in the backend? – Francesco Clementi Nov 05 '21 at 08:02
  • Yes, I get the same error through my console log – Saber Bouazzaoui Nov 05 '21 at 10:30
  • When I look at the database it sais _id: ObjectID('616ccdfb213c8b8ca70bb82c'), could this be the problem? Because it needs a reference to the objectID and not just the ID? When I navigate to my wrkout the _id:'616ccdfb213c8b8ca70bb82c' is enough, but maybe when I use a delete function I need to refer to _id: ObjectID('616ccdfb213c8b8ca70bb82c')? – Saber Bouazzaoui Nov 06 '21 at 06:55
  • It depends on which framework you are using in your backend. Usually with mongoose or loopback there is no need to specify ObjectID but it depends on how you configured the framework – Francesco Clementi Nov 06 '21 at 14:58
  • Well, after testing many times and still notfinding a solution, I found that the path ("/Workout/_id") simply can not be found, even if I put in the actual _id, d you have any idea wath the right path is to find a database item? Or is this unique for every database? – Saber Bouazzaoui Nov 07 '21 at 03:57
  • Can't help without code. Could be a bug on your backend code, a misconfiguration of the framework, a wrong id and much more. Try to post the backend code – Francesco Clementi Nov 08 '21 at 07:44
  • I had to create another path in my backend API actually for the delete function, I've finally fixed it. Thanks for the help anyway! – Saber Bouazzaoui Nov 09 '21 at 08:37

0 Answers0