Home > OS >  How to fully load data using axios before render
How to fully load data using axios before render

Time:12-02

I'm learn react, and when learn about how fetching data, i wonder, can we only render react-dom after fetch data successful, i mean if we don't get data, we wont execute any code further, i make an example here

import "./styles.css";
import axios from "axios";
import { useEffect, useState } from "react";
export default function App() {
  const [data, loadData] = useState([]);
  useEffect(() => {
    const dataRes = async () =>
      await axios
        .get("https://jsonplaceholder.typicode.com/todos/1")
        .then((res) => res.data)
        .then((data) => loadData(data));
    dataRes();
  }, []);

  console.log("data", data);
  console.log("userId", data.userId);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Above code, always return something like:

data "" 
userId 
undefined
data 
{userId: 1, id: 1, title: "delectus aut autem", completed: false}
userId 

in console! As you can see, it take a moment to fetch data and if i want to use userId, for example, it will return undefined , and maybe app will face error with this.

So my question, like mention above, how can we fully fetch data before do anything, and if i log, it always return the real data, not the unfinished one, so i can't avoid some very very annoy error like, "foo is undefined" or "bar unexpected token u in json at position 0" ==> i'm sure this error because of undefined one

Here is the codesanbox for that https://codesandbox.io/s/hopeful-framework-j4pjq?file=/src/App.tsx

Thank you so much for help

UPDATE: I forgot the second console.log , i edited

CodePudding user response:

Your code is actually okay and you can just add:

if (!data.userId) return null 
// or some spinner or just <div>Waiting for data to load...</div>

Added you example - where you do something after:

https://codesandbox.io/s/quirky-moore-cmgso

Or even better just google React Suspense - it's really cool and may solve your problems.

Error around bar unexpected token u in json at position 0 is not related and most likely due to malformed JSON, when you try using JSON.parse can happen if you don't await json maybe you have quotes inside quotes, make sure quotes are okay...lot of things can go wrong.

  • Related