How to Solve Error in giving variable to the async function?

65 views Asked by At

Iam trying to pass the number of the page in (fetchPlanets) function

put it's gets the following error

enter image description here

here is the code

import React, { useState } from 'react'
import { useQuery } from 'react-query'
import Planet from './Planet'

const fetchPlanets = async (key, page) => {
    const res = await fetch(`http://swapi.dev/api/planets/?page=${page}`)
    return res.json()
}

const Planets = () => {
    const [page, setPage] = useState(1)

    const { data, status } = useQuery(['planets', page], fetchPlanets)

    return (
        <div>
            <h2>Planets</h2>

            <button onClick={() => setPage(1)}>Page 1</button>
            <button onClick={() => setPage(2)}>Page 2</button>
            <button onClick={() => setPage(3)}>Page 3</button>

            {status === 'loading' && (
                <div>Loading Data</div>
            )}

            {status === 'error' && (
                <div>Error Fetching Data</div>
            )}

            {status === 'success' && (
                <div>
                    {data.results.map(planet => <Planet planet={planet} key={planet.name} />)}
                </div>
            )}
        </div>
    )
}
export default Planets

as you can see the variable page in async function is giving value undefined

1

There are 1 answers

0
Matt Carlotta On

When using queryKeys, you need to destructure the property from the fetcher function arguments:

const fetcher = ({ queryKey )) => {...};

or

const fetcher = props => {
  const { queryKey } = props;
  ...etc
}

Then you can use the keys based upon their position:

// queryKeys: ["planets", 1]

const [category, page] = queryKeys;

const res = await fetch(`https://swapi.dev/api/${category}/?page=${page}`);

Working example:

Edit React-Query Example


Planets.js

import React, { useState } from "react";
import { useQuery } from "react-query";
// import Planet from "./Planet";

const fetchPlanets = async ({ queryKey }) => {
  const [category, page] = queryKey;
  const res = await fetch(`https://swapi.dev/api/${category}/?page=${page}`);
  return res.json();
};

const Planets = () => {
  const [page, setPage] = useState(1);

  const { data, status } = useQuery(["planets", page], fetchPlanets);

  return (
    <div className="app">
      <h2>Planets</h2>

      <button onClick={() => setPage(1)}>Page 1</button>
      <button onClick={() => setPage(2)}>Page 2</button>
      <button onClick={() => setPage(3)}>Page 3</button>

      {status === "loading" && <div>Loading Data</div>}

      {status === "error" && <div>Error Fetching Data</div>}

      {status === "success" && (
        <pre className="code">{JSON.stringify(data.results, null, 4)}</pre>
      )}
    </div>
  );
};
export default Planets;

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import Planets from "./Planets";
import "./styles.css";

const queryClient = new QueryClient();

ReactDOM.render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <Planets />
    </QueryClientProvider>
  </StrictMode>,
  document.getElementById("root")
);