search

Home  >  Q&A  >  body text

For some reason my code only displays once and when I refresh the page I start getting errors

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.

P粉986028039P粉986028039289 days ago327

reply all(1)I'll reply

  • P粉447495069

    P粉4474950692024-02-18 15:16:59

    When you process data from the api, you should use optional chaining because the data may or may not be:

    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 (
        

    Rapid Chess

    Current Rating: {user?.[0]?.last?.rating}

    Best Rating: {user?.[0]?.best?.rating}

    Wins: {user?.[0]?.record?.win}

    Losses: {user?.[0]?.record?.loss}

    Draws: {user?.[0]?.record?.draw}

    ); }; export default SingleUser;

    reply
    0
  • Cancelreply