How do I implement a “if statement” to only load data once it has arrived?

  Kiến thức lập trình

Apologies if that is convoluting in any way. Take a look at this code:

import React from "react";
import { useFetchPlayersQuery } from "../../api/puppyBowlApi";
import '/src/index.css'

const Players = () => {
  // Use the generated hook to fetch data from the API
  // When the component is first rendered, it will start the API fetch
  // It will re-render each time the fetch status changes (e.g., "loading", "data arrived", "error")
  const { data = {}, error, isLoading } = useFetchPlayersQuery();
 
  // Show a loading message while data is being fetched
  if (isLoading) {
    <h1>Data is loading...</h1>
  }

  // Show an error message if the fetch failed
  if (error) {
    <h1>There was an error fetching data...</h1>
  }

  // Show the fetched data after it has arrived
  return (
    <div className="players">

      {isLoading?"Loading...":data.data.players.map((player) => (

        <div key={player.id} className="player-card">

          <img src={player.imageUrl} alt={player.name}></img>
          <div className="player-details">
            
            <h2>{player.name}</h2> 
            
            <p>{player.breed}</p> 
            
            <p>{player.status}</p>
          </div>
        </div>
      ))}
    </div>
  );
};


export default Players;

What I am trying to do here is use a series of “if-statements” to render the data fetched by the Redux query. Notice the turnary {isLoading?"Loading...": in front of the map. This works. I am trying to take it away and use the if-statements instead of using the turnary operators. If you all need any more information then let me know. Any help is greatly appreciated!

LEAVE A COMMENT