Using Redux to fetch an API, but return is undefined?

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

The below code uses Redux to display an array using createApi and fetchBaseQuery. The problem I am having is that when the program attempts to map over the data, it returns an error saying that “players (in Players.jsx) is undefined”. Being new to React and Redux, I can’t tell if the problem is coming from how I implemented the createApi or if it is just a syntax error somewhere.

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";


export const puppyBowlApi = createApi({
  
  reducerPath: "puppyBowlApi",

  baseQuery: fetchBaseQuery({
    baseUrl: '(REMOVED FOR SECURITY REASONS)'
  }),

  endpoints: (builder) => ({
    fetchPlayers: builder.query
    ({
      query: () => `players`,
    }),
  }),
});

export const { useFetchPlayersQuery } = puppyBowlApi;

Store:

import { configureStore } from "@reduxjs/toolkit";

import { puppyBowlApi } from "../api/puppyBowlApi";

export const store = configureStore({
  reducer: {
    [puppyBowlApi.reducerPath]: puppyBowlApi.reducer,
  },
  
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(puppyBowlApi.middleware)
});

Players.jsx where the Players component is rendered. This is where the problem lies, or at least I assume it is.

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

const Players = () => {
  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>
  }

  return (
    <div className="players">
      

      {data.data.players.map((player) => (

        <div key={player.id} className="player-card">
          
          <div className="player-details">
            
            <h2>{player.name}</h2> 
            
            <p>{player.breed}</p> 
            
            <p>{player.status}</p>
          </div>
        </div>
      ))}
    </div>
  );
};

export default Players;

App.jsx where the Players component is contained:

import React from "react";
import Players from "./features/players/Players";

function App() {
  return (
    <div className="App">
      <Players />
    </div>
  );
}

export default App;

Main.jsx where the application is rendered:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./index.css"
import { store } from "./app/store";
import { Provider } from "react-redux";

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,

);

As seen above, I have also attached my main.jsx and App.jsx just so you all can see the full process here. Any help is greatly appreciated, thank you!

LEAVE A COMMENT