0

Client/App.js:

import React, { useState, useEffect } from "react";
import Axios from "axios";
const App = () => {
  const [movieName, setmovieName] = useState("");
  const [movieReview, setmovieReview] = useState("");
  const [getReview, setgetReview] = useState([]);

  useEffect(() => {
    Axios.get("http://localhost:3001/api/get", (result) => {
      console.log(result.data);
      setgetReview(result.data);
    });
  }, []);

  const submitReview = () => {
    Axios.post("http://localhost:3001/api/insert", {
      movieName: movieName,
      movieReview: movieReview
    })
      .then(() => {
        alert("Success");
      })
      .catch((e) => alert(e));
  };
  return (
    <div className="index">
      <h2>movie name</h2>{" "}
      <input type="text" onChange={(e) => setmovieName(e.target.value)} />
      <h2>movie rating</h2>{" "}
      <input type="text" onChange={(e) => setmovieReview(e.target.value)} />
      <button onClick={submitReview}>submit</button>
      {getReview.map((val) => {
        return (
          <h1>
            Movie name : {val.movieName} Movie review: {val.movieReview}
          </h1>
        );
      })}
    </div>
  );
};

export default App;

Server/index.js:

const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
  host: "localhost",
  root: "root",
  password: "",
  database: "crudatabase"
});

db.connect((err) => {
  if (err) throw err;
});

app.get("/api/get", (req, res) => {
  const selectStmt = "SELECT movieName,movieReview FROM movie_review;";
  db.query(selectStmt, (err, result) => {
    res.send(result);
  });
});

app.post("/api/insert", (req, res) => {
  const movieName = req.body.movieName;
  const movieReview = req.body.movieReview;
  const insertStmt =
    "INSERT INTO movie_review (movieName,movieReview) VALUES (?,?);";
  db.query(insertStmt, [movieName, movieReview], (err, result) => {
    console.log(err);
  });
});

app.listen(3001, () => {
  console.log("Server running on 3001");
});

In the above react and express code I am able to insert the data in the database but after inserting then() part in client is not working. Also the useEffect is not working. I tried many ways but not able to get the reason. I would be glad if someone can solve me the error and all the dependencies are already installed.

2
  • In express and in the insert method you did not send any response with res.send method and client does not recieve any response from server. Commented Dec 13, 2021 at 14:13
  • you are not sending back the response from your /insert API res.end({status:'success'}) Commented Dec 13, 2021 at 14:13

3 Answers 3

2
  1. In your useEffect, you're passing a callback to Axios.get - this is not consistent with the Axios API (you even do it correctly in the submitReview function!):
useEffect(() => {
    // change to Promise.then() chain
    Axios.get("http://localhost:3001/api/get").then((result) => {
      console.log(result.data);
      setgetReview(result.data);
    });
  }, []);
  1. Your then() chain is not working because your POST response handler never returns a status or a response! Just like in your GET handler, your POST handler needs to let the client know that a request has been successful. e.g. res.send(/*...*/) or even just res.sendStatus(200).
Sign up to request clarification or add additional context in comments.

Comments

0

As you are dealing with the promise and have used the thenable syntax while submitting the values but you are not using it while getting the values. try using the below code and check whether this resolves your problem. One more concise method to deal with promises is to use async/await try to use the below code hopes this resolves your problem.

    useEffect(() => {
    const getMovies = async () => {
      try {
        let { data } = await Axios.get("http://localhost:3001/api/get");
        console.log(data);
        setgetReview(data);
      } catch (error) {
        console.log(error);
      }
    };

    getMovies();
  }, []);

Comments

0

Your useEffect is returning a promise try to use async await or .then on your code.

Try to change it from:

useEffect(() => {
        Axios.get("http://localhost:3001/api/get", (result) => {
          console.log(result.data);
          setgetReview(result.data);
        });
      }, []);

To:

useEffect(() => {
      const get_data = async () => {
         try {
           const result = await Axios.get("http://localhost:3001/api/get")
           console.log(result.data)
           setgetReview(result.data)
         } catch (e) {
           console.log(e)
         }
      }

      get_data()
}, []);

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.