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
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" />} </>;
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