Home > Blockchain >  React useEffect and Axios fetching object array results and displaying on frontend
React useEffect and Axios fetching object array results and displaying on frontend

Time:08-12

I'm trying to use React's useEffect() to GET data with Axios from the Express backend server. I'm able to console.log the response on the frontend (screenshot included). However I'm not able to map the array and display the items on the frontend.

I want the data from the results array to display on the frontend cards and create a list of cards when mapping thought the array.

React Frontend:

import React, { useEffect, useState } from "react";
import "./App.css";
import axios from "axios";

function App() {
  const [results, setResults] = useState([]);

  //Test: onClick handler to get the data from the server backend
  //and display the response on the frontend(console window).
  // const getHealthData = async () => {
  //         axios.get("/health")
  //         .then(res => {
  //           console.log(res.data.results) //success
  //         }).catch(err => {
  //           console.log(err);
  //         })
  //       }

  useEffect(() => {
    setTimeout(() => {
      const fetchResults = async () => {
        try {
          const response = await axios.get("/health"); //http://localhost/3000/health
          setResults(response.data.results);
        } catch (err) {
          console.log(err);
        }
      };

      fetchResults();

    }, 60000); //1 minute timeout
  }, [results]);

  return (
    <div>
      <div className="container">
        //Testing API call with onClick
        {/* <button onClick={getHealthData}>Get Health Data</button> */}

        // I want to map through the results data and return the object key values into the card.

       {results.map((result, index) => ( 
        
        <div key={index} className="card">
          <h2 className="card-title">Health</h2>
          <p className="card-text">Checker: {result.checker}</p>
          <p className="card-text">Output: {result.output}</p>
          <p className="card-text">Passed: {result.passed}</p>
          <p className="card-text">Timestamp: {result.timestamp}</p>
          <p className="card-text">Expires: {result.expires}</p>
        </div>
      ))};
      </div>

  );
}

export default App;

Express backend server(proxy):

const express = require('express');
const app = express();
const axios = require('axios');
const cors = require('cors'); 
require('dotenv').config();
const PORT = 5000;

app.use(cors({}))

app.get(':endpoint([\\/\\w\\.-]*)', function(req, res){ 

    let endpoint = process.env.LOCALHOST_URL   req.params.endpoint;

    axios.get(endpoint).then(response => {
        console.log(response.data);
        res.json(response.data)
    }).catch(error => {
        res.json(error.message)
    })
});


app.listen(PORT, function() {
    console.log("Server started on 'http://localhost:5000'")
})

JSON REST Api Sample:

{
  hostname: '23c10882746a',
  status: 'success',
  timestamp: 1660297130.9966166,
  results: [
    {
      checker: 'postgres_available',
      output: 'Postgres OK',
      passed: true,
      timestamp: 1660297113.0233154,
      expires: 1660297140.0233154
    },
    {
      checker: 'message_queue_available',
      output: 'Message Queue OK',
      passed: true,
      timestamp: 1660297113.0477347,
      expires: 1660297140.0477347
    },
    {
      checker: 'disk_space_enough',
      output: '232 GB Free out of 314 GB Total. 73.9% remaining',
      passed: true,
      timestamp: 1660297113.0478468,
      expires: 1660297140.0478468
    }
  ]
}

I've also included a screenshot of the data in the browser.

Chrome Browser Network Preview

CodePudding user response:

You have a typo in your map() call. Try replacing results with result:

<div key={index} className="card">
  <h2 className="card-title">Health</h2>
  <p className="card-text">Checker: {result.checker}</p>
  <p className="card-text">Output: {result.output}</p>
  <p className="card-text">Passed: {result.passed}</p>
  <p className="card-text">Timestamp: {result.timestamp}</p>
  <p className="card-text">Expires: {result.expires}</p>
</div>

CodePudding user response:

results variable does not exists, your data is stored inside health state. And you also have typo inside your map function, use result instead.

health.map(result, index...)
  • Related