Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
How to fully load data using axios before render

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda