Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda