All CRUD operations work except POST. Why?

Joined
Sep 12, 2022
Messages
39
Reaction score
0
I tested with Postman and all the CRUD operations work, even POST, but only POST does not work in the frontend app, I've debugged for hours but I get the error. Uncaught (in promise) AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}code: "ERR_BAD_RESPONSE"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Request failed with status code 500"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: {…}, status: 500, statusText: '', headers: AxiosHeaders, config: {…}, …}stack: "AxiosError: Request failed with status code 500\n at settle (webpack-internal:///(app-client)/./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///(app-client)/./node_modules/axios/lib/adapters/xhr.js:121:66)"[[Prototype]]: Error

Here's my code

JavaScript:
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const url = "https://leader-board-backend.vercel.app/api/v1/score/";
const initialState = {
  details: [],
  isLoading: true,
};
export const getScores = createAsyncThunk("score/getScores", async () => {
  try {
    const { data } = await axios(url);
    console.log(`SERVER DATA`);
    console.log(data);
    return data;
  } catch (error) {
    console.log(error.response);
    throw error;
  }
});
const scoreSlice = createSlice({
  name: "score",
  initialState,
  reducers: {
    addDetails: {
      reducer(state, action) {
        state.details.push(action.payload);
      },
      prepare(name, exactScore) {
        return {
          payload: {
            name,
            exactScore,
          },
        };
      },
    },
    updateDetails(state, action) {
      const { _id, ...formData } = action.payload;
      state.details = state.details.map((item) =>
        item._id === _id ? { ...item, ...formData } : item
      );
    },
    deleteDetails: (state, action) => {
      const id = action.payload;
      state.details = state.details.filter((item) => item._id !== id);
    },
  },
  extraReducers(builder) {
    builder
      .addCase(getScores.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(getScores.fulfilled, (state, action) => {
        state.isLoading = false;
        state.details = action.payload;
      })
      .addCase(getScores.rejected, (state) => {
        state.isLoading = false;
      });
  },
});
export const isLoading = (state) => state.isLoading;
export const { addDetails, deleteDetails, updateDetails } = scoreSlice.actions;
export default scoreSlice.reducer;

,

JavaScript:
import { configureStore } from "@reduxjs/toolkit";
import scoreReducer from "./features/score/scoreSlice";

export const store = configureStore({
  reducer: {
    score: scoreReducer,
  },
});

,

JavaScript:
import axios from "axios";
import { useDispatch } from "react-redux";
import { useState } from "react";
import {
  deleteDetails,
  updateDetails,
} from "../store/features/score/scoreSlice";
export const Score = ({ _id, name, exactScore }) => {
  const dispatch = useDispatch();
  const [editMode, setEditMode] = useState(false);
  const [formdata, setFormData] = useState({
    name: name,
    exactScore: exactScore,
  });
  async function handleDelete() {
    const url = `https://leader-board-backend.vercel.app/api/v1/score/${_id}`;
    try {
      const { data } = await axios.delete(url);
      dispatch(deleteDetails(_id));
      return data;
    } catch (error) {
      console.log(error.response);
      throw error;
    }
  }
  function handleEdit() {
    setEditMode(!editMode);
  }
  function handleChange(event) {
    const { name, value } = event.target;
    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
  }
  async function handleSubmit(event) {
    event.preventDefault();
    const url = `https://leader-board-backend.vercel.app/api/v1/score/${_id}`;
    try {
      await axios.patch(url, formdata);
      dispatch(updateDetails({ _id, ...formdata }));
      setEditMode(false);
    } catch (error) {
      console.log(error.response);
      throw error;
    }
  }
  return (
    <div>
      {editMode ? (
        <form onSubmit={handleSubmit}>
          <label htmlFor="name" className="form-label">
            Name
          </label>
          <input
            type="text"
            id="name"
            name="name"
            value={formdata.name}
            onChange={handleChange}
            className="form-control"
            aria-describedby="name"
          />
          <label htmlFor="exactScore" className="form-label">
            Score
          </label>
          <input
            type="text"
            id="exactScore"
            name="exactScore"
            value={formdata.exactScore}
            onChange={handleChange}
            className="form-control"
            aria-describedby="exactScore"
          />
          <button type="submit" className="btn btn-success mt-1">
            Save
          </button>
        </form>
      ) : (
        <div
          className="card text-left my-2"
          style={{ backgroundColor: "white" }}
        >
          <div className="row card-body">
            <div className="col">
              <p style={{ margin: 0, padding: 0 }}>{name}</p>
            </div>
            <div className="col">
              <p style={{ margin: 0, padding: 0 }}>{exactScore}</p>
            </div>
            <div className="col col-lg-2">
              <button
                onClick={handleEdit}
                className="me-3 rounded-circle bg-success border border-0 text-light"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  fill="currentColor"
                  class="bi bi-pencil-square"
                  viewBox="0 0 16 16"
                >
                  <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
                  <path
                    fill-rule="evenodd"
                    d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"
                  />
                </svg>
              </button>
              <button
                onClick={handleDelete}
                className="mx-3 rounded-circle bg-danger border border-0 text-light"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  fill="currentColor"
                  class="bi bi-trash"
                  viewBox="0 0 16 16"
                >
                  <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6Z" />
                  <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1ZM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118ZM2.5 3h11V2h-11v1Z" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

,

"use client";
import { useEffect } from "react";
import { ScoreContainer } from "./components/ScoreContainer";
import { getScores } from "./store/features/score/scoreSlice";
import { useDispatch } from "react-redux";
import { PostScore } from "./components/PostScore";
import "bootstrap/dist/css/bootstrap.min.css";
export default function Home() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getScores());
}, []);
return (
<main className="container-lg">
<PostScore />
<div className="card">
<div className="row card-body">
<div className="col">
<h6 style={{ margin: 0, padding: 0 }}>Name</h6>
</div>
<div className="col">
<h6 style={{ margin: 0, padding: 0 }}>Score</h6>
</div>
<div className="col col-lg-2">
<h6 style={{ margin: 0, padding: 0 }}>Edit/Delete</h6>
</div>
</div>
</div>
<ScoreContainer />
</main>
);
}

,

JavaScript:
"use client";
import "./globals.css";
import { Inter } from "next/font/google";
import { store } from "./store/store";
import { Provider } from "react-redux";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <Provider store={store}>
        <body
          style={{
            minHeight: "100vh",
            maxHeight: "fit-content",
            boxSizing: "border-box",
            backgroundColor: "#f2f5fd",
            width: "100vw",
          }}
        >
          {children}
        </body>
      </Provider>
    </html>
  );
}

,

JavaScript:
import { useSelector } from "react-redux";
import { Score } from "./Score";
export const ScoreContainer = () => {
  const data = useSelector((state) => state.score.details);
  const m = data.map((value) => (
    <Score
      key={value._id}
      _id={value._id}
      name={value.name}
      exactScore={value.exactScore}
    />
  ));
  return <div>{m}</div>;
};

,

JavaScript:
import { useState } from "react";
import axios from "axios";
import { useDispatch } from "react-redux";
import { addDetails } from "../store/features/score/scoreSlice";
export const PostScore = () => {
  const dispatch = useDispatch();
  const [formdata, setFormData] = useState({
    _id: "",
    name: "",
    exactScore: "",
  });
  function handleChange(event) {
    const { name, value } = event.target;
    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
  }

  async function handleSubmit(event) {
    event.preventDefault();
    const url = "https://leader-board-backend.vercel.app/api/v1/score/";
    try {
      const { data } = await axios.post(url, formdata);
      dispatch(addDetails(data.name, data.exactScore));
    } catch (error) {
      console.log(error.response);
      throw error;
    }
    setFormData({ name: "", exactScore: "" });
  }

  return (
    <form
      className="py-3 d-flex justify-content-center align-items-center gap-3"
      style={{ boxSizing: "border-box" }}
    >
      <label htmlFor="name" className="fw-bold form-label">
        Name
      </label>
      <input
        type="text"
        id="name"
        name="name"
        onChange={handleChange}
        className="form-control"
        aria-labelledby="name"
      />
      <label htmlFor="exactScore" className="fw-bold form-label">
        Score
      </label>
      <input
        type="text"
        id="exactScore"
        name="exactScore"
        onChange={handleChange}
        className="form-control"
        aria-labelledby="exactScore"
      />
      <button
        type="submit"
        onClick={handleSubmit}
        className="btn btn-primary rounded-pill fw-bold"
        style={{ width: "24rem" }}
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="16"
          height="16"
          fill="currentColor"
          class="bi bi-plus-lg"
          viewBox="0 0 16 16"
          style={{ color: "white" }}
          className="text-white"
        >
          <path
            fill-rule="evenodd"
            d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2Z"
            style={{ color: "white" }}
            className="text-white"
          />
        </svg>
        Post
      </button>
    </form>
  );
};

,

JavaScript:
{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.5",
    "axios": "^1.4.0",
    "bootstrap": "^5.2.3",
    "bootstrap-icons": "^1.10.5",
    "next": "13.4.4",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-redux": "^8.0.5"
  }
}
 
Joined
Sep 4, 2022
Messages
128
Reaction score
16
hello !

the error message is '500' type.
the fault happen at server code level.

in a first step, the main error should be a 'syntax error' causing trouble in your code which is call.
 
Joined
Sep 12, 2022
Messages
39
Reaction score
0
hello !

the error message is '500' type.
the fault happen at server code level.

in a first step, the main error should be a 'syntax error' causing trouble in your code which is call.
It's no caused by server error. It caused by here

JavaScript:
  async function handleSubmit(event) {
    event.preventDefault();
    const url = "https://leader-board-backend.vercel.app/api/v1/score/";
    try {
      const { data } = await axios.post(url, formdata);
      dispatch(addDetails(data.name, data.exactScore));
    } catch (error) {
      console.log(error.response);
      throw error;
    }
    setFormData({ name: "", exactScore: "" });
  }

and how it sends this data

JavaScript:
  const [formdata, setFormData] = useState({
    _id: "",
    name: "",
    exactScore: "",
  });

when I convert each to individual states.
JavaScript:
  const [name, setName] = useState("");
  const [exactScore, setExactScore] = useState("");

,


JavaScript:
  async function handleSubmit(event) {
    event.preventDefault();
    const url = "https://leader-board-backend.vercel.app/api/v1/score/";
    try {
      const { data } = await axios.post(url, { name, exactScore });
      dispatch(addDetails(data.name, data.exactScore));
    } catch (error) {
      console.log(error.response);
      throw error;
    }
    setName("");
    setExactScore("");
  }

it works just fines but causes other bugs in the handle edit and delete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top