Displaying RapidAPI response data in React components instead of raw JSON

I’m working on a full stack application using an Express backend and a React frontend. I’ve successfully connected to a RapidAPI service, and my server is receiving the data correctly. However, the problem I’m experiencing is that the data appears as raw JSON on my page rather than being properly rendered in my React components.

My backend is set up and functioning properly—it retrieves data from the API and sends it to the frontend. Yet, I’m unsure about how to effectively consume this data in my React app and present it in a way that’s user-friendly.

Backend code (server.js):

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

const app = express();
const PORT = 3001;

app.use(cors());

app.get('/sports-data', async (req, res) => {
  const config = {
    method: 'GET',
    url: 'https://api-football-v1.p.rapidapi.com/v3/fixtures',
    params: {
      league: '140',
      season: '2023',
      team: '42'
    },
    headers: {
      'X-RapidAPI-Key': process.env.API_KEY,
      'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com'
    }
  };
  
  try {
    const result = await axios.request(config);
    console.log(result.data);
    res.json(result.data);
  } catch (err) {
    console.error(err);
  }
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Frontend code (Main.js):

import React from 'react';

function Main() {
  return (
    <div>
      {/* Need help implementing data display here */}
    </div>
  );
}

export default Main;

What is the best approach to retrieve this data in my React component and display it correctly instead of showing raw JSON?

The Problem:

You’re finding that your React frontend is displaying raw JSON data from your Express backend instead of rendering it in a user-friendly format. Your backend correctly fetches data from a RapidAPI service, but the frontend doesn’t know how to process and display this data effectively.

:thinking: Understanding the “Why” (The Root Cause):

The issue stems from a missing step in your React application: you’re fetching the data correctly, but you haven’t implemented the logic to process the JSON response and render it within your React components. The raw JSON is displayed because React doesn’t inherently know how to interpret and visually represent the data structure. You need to use React’s state management capabilities (useState and useEffect) to fetch the data, then map through that data to display the relevant information within your JSX.

:gear: Step-by-Step Guide:

Step 1: Fetch and Manage Data in React:

Modify your Main.js component to fetch the data from your backend and manage it using React’s state:

import React, { useState, useEffect } from 'react';

function Main() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('/sports-data');
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  //Example: Assuming your API returns an array of fixtures
  if (data && data.response && Array.isArray(data.response)) {
    return (
      <div>
        {data.response.map((fixture) => (
          <div key={fixture.fixture.id}>
            <h3>{fixture.teams.home.name} vs {fixture.teams.away.name}</h3>
            <p>Date: {fixture.fixture.date}</p>
            {/* Add other relevant fields as needed */}
          </div>
        ))}
      </div>
    );
  } else {
    return <div>No data available or unexpected data format.</div>;
  }
}

export default Main;

Step 2: Inspect Your API Response:

Before rendering the data, use console.log(data) in your Main.js component to examine the structure of the JSON response from your backend. This will help you understand how to correctly access the specific fields you want to display (e.g., team names, dates, scores). Adjust the rendering logic in Main.js to match your data structure.

:mag: Common Pitfalls & What to Check Next:

  • Data Structure: The structure of your API response is crucial. Thoroughly inspect the JSON structure using console.log to understand how the data is nested before trying to extract it in your React component. Ensure that the keys you are accessing in your map function (fixture.teams.home.name, etc.) exist in your API response.
  • Error Handling: The provided code includes basic error handling. Consider adding more robust error handling to provide more informative messages to the user if the API request fails.
  • Loading State: Displaying a “Loading…” message while fetching data improves the user experience.
  • Backend Route: Double-check that your backend route (/sports-data) is correctly configured and handles potential errors gracefully.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

You need to fix how you’re handling the API call in React. Set up a fetch request to your backend and manage the response with state. In Main.js, use useState to initialize state and make the API call in useEffect. The main issue is probably how you’re rendering the data once it comes back. Don’t try to display the entire object - extract specific fields from the response instead. For football fixtures, you’ll want something like response[0].fixture.date, response[0].teams.home.name, etc. (depends on your API structure). Don’t forget error handling and loading states too. I ran into the same thing with sports APIs - the data gets pretty nested, so console.log the response first to see what you’re working with.

Had this exact issue when I started with RapidAPI endpoints. You’re not actually fetching data from your backend in React yet. You need a component that handles the API call and renders the data properly. Create a function that fetches from your ‘/sports-data’ endpoint and parse the response structure carefully. Football APIs usually nest data under a ‘response’ array, so data.response[0] will give you the actual fixture info. Handle loading states while fetching data, or users will see a blank page. Structure your component to show specific fields like match date, team names, and scores instead of trying to render the entire JSON object. Understanding the API response structure is key before displaying it.

yeah, just use useEffect and useState to fetch the data. u can do const [data, setData] = useState([]) and then add useEffect(() => { fetch('/sports-data').then(res => res.json()).then(setData) }, []). then just map through the data to show it.

the main thing ur missing is calling ur backend from react. since your server’s already runnning, ur halfway there. add a useEffect to your Main component that fetches from http://localhost:3001/sports-data, then store the response with setState. dont dump the entire json response on screen - pull out specific stuff like team names or fixture dates first.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.