user8317490
user8317490

Reputation:

Reactjs - Data is being fetched multiple times

HI all I recently started using react and I have a simple question, I have this function that is supposed to fetch content and it stores the response in the variable data. after the page load when I console log it I see that the data is being fetched multiple times, when I refresh it it's loading a couple more times again. How do I fix this?

import {useQuery} from "react-query";
import axios from "axios";

const fetchBrands = async () =>{
     const res = await axios.get("APIURL");
    return res.data;
}
export default function LoadBrands() {
    const {data, status} = useQuery('getbrand', fetchBrands);
    return(
    <>
     {status === 'loading' && <div>Loading</div>}
      {status === 'error' && <div>Error Loading</div>}
      {status === 'success' && <div>YUPP</div>}
      {console.log(data)}
    </>
    )
}

Upvotes: 3

Views: 10509

Answers (1)

keysl
keysl

Reputation: 2167

So hey there's few wrong here You are using react-query but you are not using any query caching making to call api at each re-render if there's a state changes.

Also the console.log at the view layer is not a good indicator that its fetching the data the console from fethbrand function is much more accurate

/* eslint-disable jsx-a11y/anchor-is-valid */
import React from "react";
import ReactDOM from "react-dom";
import { useQuery, QueryCache, ReactQueryCacheProvider } from "react-query";
import axios from "axios";

const queryCache = new QueryCache();

const fetchBrands = async () => {
  const res = await axios.get(
    "https://api.github.com/repos/tannerlinsley/react-query"
  );
  console.log("test here if it will call api");
  return res.data;
};

function LoadBrands() {
  const { data, status } = useQuery("getbrand", fetchBrands);
  return (
    <>
      {status === "loading" && <div>Loading</div>}
      {status === "error" && <div>Error Loading</div>}
      {status === "success" && <div>YUPP</div>}
      {console.log(data)}
    </>
  );
}

export default function App() {
  return (
    <ReactQueryCacheProvider queryCache={queryCache}>
      <LoadBrands />
    </ReactQueryCacheProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

heres the fiddle : https://codesandbox.io/s/bold-dawn-huudy?file=/src/index.js

Upvotes: 2

Related Questions