Home > Net >  How to fetch data before render functionnal component in react js
How to fetch data before render functionnal component in react js

Time:12-15

Here Below my code I would like to retrieve all data before starting the render of my component, is there any way to do that in react ? I guess it's maybee a simple code line but as I'm new in coding I still don't know all react components behavior. Thanks for your answer.

import { useState, useEffect } from "react";
import axios from "axios";
import Cookies from "js-cookie";
// import material ui
import CircularProgress from "@mui/material/CircularProgress";
import Box from "@mui/material/Box";
// import config file
import { SERVER_URL } from "../../configEnv";

const Products = ({ catList }) => {
  // catList is data comming from app.js file in format Array[objects...]
  console.log("catList ==>", catList);
  const [isLoading, setIsLoading] = useState(true);
  const [dataSku, setDataSku] = useState([]);

  console.log("datasku ==>", dataSku);

  const tab = [];
  useEffect(() => {
    // Based on the catList tab I fetch additionnal data linked with each object of catList array
    catList.slice(0, 2).forEach(async (element) => {
      const { data } = await axios.post(`${SERVER_URL}/products`, {
        product_skus: element.product_skus,
      });

      // The result I receive from the call is an array of objects that I push inside the Tab variable
      tab.push({ name: element.name, content: data });
      setDataSku(tab);
      console.log("tab ==>", tab);
      setIsLoading(false);
    });
  }, [catList]);

  return isLoading ? (
    <Box sx={{ display: "flex" }}>
      {console.log("there")}
      <CircularProgress />
    </Box>
  ) : (
    <div className="products-container">
      <div>LEFT BAR</div>
      <div>
        {dataSku.map((elem) => {
          return (
            <div>
              <h2>{elem.name}</h2>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default Products; ```

CodePudding user response:

@Jessy use your loading state to fetch data once,

In your useEffect, check for loading,

useEffect(() => {
  if(loading) {
    catList.slice(0, 2).forEach(async (element) => {
      const { data } = await axios.post(`${SERVER_URL}/products`, {
        product_skus: element.product_skus,
      });
      tab.push({ name: element.name, content: data });
      setDataSku(tab);
      console.log("tab ==>", tab);
      setIsLoading(false);
    });
   }
  }, [catList]);`

CodePudding user response:

I finally managed to displayed all results by adding this condition on the isLoading

if (tab.length === catList.length) {
          setIsLoading(false);
        }

Many thanks guys for your insight :)

  • Related