Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!