Home > Software engineering >  How to render component only when data is fetched from API?
How to render component only when data is fetched from API?

Time:01-16

I've had a problem with refreshing page in react app with using context api. After refreshing page in my console I see this logs:

enter image description here

my context fetch data from rest api but only the third time by what cause that my span is empty after end refreshing page :/

Here is my component with using data from context api.

Header/index.tsx

  const { currentAccount } = useContext(AppContext);
  console.log("ACCOUNT: ", currentAccount);

  return (
       <span>{currentAccount?.name}</span>
  );

This is my applicationContext

ApplicationContext.tsx

  useEffect(() => {
    checkLogin();
  }, []);

  const checkLogin = async () => {
    console.log("checkLogin");

    setLoggedIn(false);

    const token = localStorage.getItem("session");

    if (token) {
      const decode = jwt(token);
      const query = {
        id: decode["id"]
      };
      const response: Account = await axios.get("/auth/account", query);
      setCurrentAccount(response);
      setLoggedIn(true);
    } else {
      setCurrentAccount(null);
      setLoggedIn(false);
    }
  }

Here is also my routing from App.tsx

        <AppContextProvider>
          {publicRouting.map(({ path, component }, i) => (
            <Route key={i} path={path} component={component} />
          ))}
          <Main>
            {privateRouting.map(({ path, component }, i) => (
              <Route key={i} path={path} component={component} />
            ))}
          </Main>
        </AppContextProvider>

can someone tell me how to render component only when data is already fetched from my rest api? All of this is doing async so I need to wait until data is coming to app

thanks for any help!

CodePudding user response:

Me, personally, like to take the following approach when rendering this type of thing:


const RenderOnFetch = () => {
    const [data, setData] = useState({});
    const [isLoading, setIsLoading] = useState(false);

    useEffect(async () => {
        await setIsLoading(true);
        const fetchedData = await fetchData();
        setData(fetchedData);
        await setIsLoading(false);
    }, []);

    return (
    <>
        {isLoading && <p>Data is being loaded..</p>}
        {!isLoading && <p>Data has been fetched..</p>}
    </>
    )

}

  •  Tags:  
  • Related