Displaying RapidAPI response data in React components

I’m working on a full-stack application using an Express backend alongside a React frontend. I’ve managed to connect to a RapidAPI service and can fetch data on my server, but I’m having a hard time correctly rendering this data in my React components rather than just outputting the raw JSON.

Backend setup (index.js):

const PORT = 3000;
const express = require('express');
const server = express();
const cors = require('cors');
require('dotenv').config();
const axios = require('axios');
server.use(cors());

server.get('/sports-data', async (req, res) => {
    const config = {
        method: 'GET',
        url: 'https://api-football-v1.p.rapidapi.com/v3/leagues/standings',
        params: {
          league: '140',
          season: '2023',
          team: '529'
        },
        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);
    }
});

server.listen(PORT, () => {
    console.log('Server running on port ' + PORT);
});

Frontend component (Main.js):

import React from 'react';

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

export default Main;

How can I fetch this data from my Express server and render it nicely in my React component?

Use the useEffect and useState hooks to fetch and manage your API data. Here’s a working example:

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

function Main() {
  const [sportsData, setSportsData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('http://localhost:3000/sports-data')
      .then(response => response.json())
      .then(data => {
        setSportsData(data);
        setLoading(false);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  if (!sportsData) return <div>No data available</div>;

  return (
    <div>
      <h2>League Standings</h2>
      {sportsData.response && sportsData.response.map((item, index) => (
        <div key={index}>
          <h3>{item.league.name}</h3>
          <p>Position: {item.league.standings[0][0].rank}</p>
          <p>Points: {item.league.standings[0][0].points}</p>
        </div>
      ))}
    </div>
  );
}

export default Main;

Make sure you understand your API’s response structure first. Log the response to see how the data’s nested - it’ll save you headaches later.

you’re missing the fetch call in ur react component. install axios on the frontend with npm install axios, then use axios.get('http://localhost:3000/sports-data') inside a useEffect hook. make sure you handle errors or ur app will crash when the API goes down.

You’re struggling with nested response structures from the Football API - I get it. Sports APIs have crazy deep nesting that’s confusing at first. After you fetch the data with useState and useEffect, check the response format carefully. For standings data, you’ll typically find team details at data.response[0].league.standings[0]. Throw in some error boundaries since API structures change without warning. Add loading states too - these calls can be slow. Start by console.logging the full response to see exactly where your data lives, then build reusable components for wins, losses, goal differences, etc.

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