import React from "react"; import { useParams } from "react-router-dom"; import { useState, useEffect } from "react"; const SingleUser = () => { const [user, setUser] = useState([]); const { username } = useParams(); useEffect(() => { const getSingleUser = async () => { try { const res = await fetch( `https://api.chess.com/pub/player/${username}/stats` ); const data = await res.json(); const heroesArray = Object.values(data); setUser(heroesArray); console.log(heroesArray[0].last); } catch (error) { console.error(error); } }; getSingleUser(); }, []); return ( <section> <div> <h1>Rapid Chess</h1> <p>Current Rating: {user[0].last.rating}</p> <p>Best Rating: {user[0].best.rating} </p> <div> <p>Wins: {user[0].record.win} </p> <p>Losses: {user[0].record.loss} </p> <p>Draws: {user[0].record.draw} </p> </div> </div> </section> ); }; export default SingleUser;
For some reason my code only displays once and when I refresh the page I start getting errors. I think this has something to do with useEffect but I don't know
TypeError: Cannot read property of undefined (read 'last'). I'm getting these errors.
When you process data from the api, you should use optional chaining because the data may or may not be: