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

212
Vistas
React: API call fails when I refresh the page

Here is my code:

import Base from "./Base";
import axios from "axios";
import { createData } from "../../utils";
import { useState, useEffect } from "react";

export default function Today(props) {
  const [scoops, setScoops] = useState(0);

  //Fetch api/scoops/today
  const fetchScoops = async () => {
    const res = await axios.get("http://localhost:8000/api/scoops/today/");
    setScoops(res.data);
  };
  useEffect(() => {
    fetchScoops();
  }, []);

  console.log(scoops[0]);

  const rows = [
    createData(0, 1, scoops[0].title, "http://example.com"),
    createData(1, 2, "Paul McCartney", "http://example.com"),
    createData(2, 3, "Tom Scholz", "http://example.com"),
    createData(3, 4, "Michael Jackson", "http://example.com"),
    createData(4, 5, "Bruce Springsteen", "http://example.com"),
  ];

  return <Base rows={rows} duration="Today" />;
}

Here is what the console returns:

> undefined
> Today.js:20 {url: 'http://localhost:8000/api/scoops/1/', title: 'Hello World!', rank: 0, created_at: '2021-10-05T04:44:52.027336Z', updated_at: '2021-10-05T04:44:52.027336Z'}

The problem is when I refresh the page, I get the following error message:

TypeError: Cannot read properties of undefined (reading 'title')

Help would be much appreciated!

Update: Optional chaining solved the issue, this works great.

scoops[0]?.title
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can set the initial scoops state to []

const [scoops, setScoops] = useState([]);

render scoops when data fetched using conditionalRendering

return <> {scoops.lenght > 0 && <Base rows={rows} duration="Today" />} </>;
about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem is, you are initializing scoops as 0 but using it like an array: scoops[0]

Try initializing scoops as an empty array. So something like this should work:

const [scoops, setScoops] = useState([]);

Also, where you are doing this: scoops[0].title you should instead use Optional chaining and use scoops[0]?.title

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