Skip to content
Advertisement

Integrate Nodejs Backend with React Frontend App

I am building an app that uses node.js for backend and react for frontend. In the backend, i have 2 functions that implement a post request.

In my react function:

  1. I want to show a spinner while waiting for the response data from the API request.

  2. For the triggerGrading function which only returns ok if successful, I want to be able to return a custom message in the frontend.

Here are my functions, and they work fine on postman. However, I am experimenting with NodeJS and React and want to know if there’s any further logic I need to add to these backend functions to be able to accurately implement the spinner and a custom message return in the UI?

grading.js

const BASE_URL = htttp://localhost:8080

const postSubject = async (req, res, next) => {
  const headers = {
    "Score-API-Version": "v2",
    "Content-type": "application/json",
  };
  const body = { name: 'Adam Lawrence' };
  try {
    const resp = await axios.post(`${BASE_URL}/subject`, body, { headers });
    const response = resp.data;
    res.send(response);
  } catch (err) {
    if (err.response) {
      res.status(err.response.status).send(err.response.data);
    } else if (err.request) {
      res.send(err.request);
    }
    next(err);
  }
};


const triggerGrading = async (req, res, next) => {
  const { id } = req.params;
  const headers = {
    "Content-type": "application/json",
    "Score-API-Version": "v2",
  };
  try {
    const resp = await axios.post(`${BASE_URL}/start/${id}`, { headers });
    const response = resp.data;
    res.send(response);
  } catch (err) {
    if (err.response) {
      res.status(err.response.status).send(err.response.data);
    } else if (err.request) {
      res.send(err.request);
    }
    next(err);
  }
};

server.js

const express = require("express");
const flows = require("./grading.js");
const cors = require("cors");
const app = express();
app.use(cors());
const PORT = 5050;
app.use(express.json());

app.listen(PORT, () => {
  console.log(`Running this application on the PORT ${PORT}`);
});


app.post("/subject", grading.postSubject);

Advertisement

Answer

React query is very easy comfy, but if you just want to explore a little bit on your own you can play with this example in codepen. In order to show a spinner while the request is being made you can use useState:

const handleClickSpin = async()=>{
setIsLoading(true)
await postSubject()
setIsLoading(false)

}

and then conditionally show the spinner. For the second part of your question, I assumed you didn’t want to send the custom message from your sever, so I just added another flag with conditional rendering.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement