react facing error when want to get specific value from back-end

Viewed 28

I am trying to get value from the back-end, it shows totally fine and grabs all the properties in the console, but when I want to access a particular value it shows an error, but sometimes it's working I have tried with useEffect dependencies but still same, the error is: Uncaught TypeError: Cannot read properties of undefined (reading 'eventName') example JSON format:

0:{ eventFeeStudent: "34" eventName: "New event" eventNotificationsDate: "2022-05-23T18:00:00.000Z" }

here it's working fine but when want to catch any specific key pair like eventName I am getting error.

const EventEditNavbar = () => {
  const { user } = useAuth();
  const [userInfo, setUserInfo] = useState({});
  console.log(userInfo);
  console.log(user);
  // console.log(userInfo[0].eventName);
  const eventName = userInfo[0].eventName;




  useEffect(() => {
    if (!user || !user.email) return
    const uri = `http://localhost:5000/findevents/?userEmail=${user.email}`;
    fetch(uri)
      .then((res) => res.json())
      .then((data) => setUserInfo(data));
  }, [user]);

  return (
    <Container>
      <div className="eventEdit_nav">
        <div className="eventEdit_nav_right">
          <Link to={`/festivals/${eventName}`}>View</Link>
          <Link to="/">Edit</Link>
          <Link to="">Manage</Link>
          <Link to="">Marketing</Link>
        </div>
        <div className="eventEdit_nav_left">
          <Link to="">Save</Link>
          <Link to="">List Event</Link>
        </div>
      </div>
    </Container>
  );
};

export default EventEditNavbar;
1 Answers

Keep in mind whenever an object's property is undefined accessing its child will throw an uncaught error, which means there is nothing beneath an undefined property.

In your case, you are initiating the userInfo with an empty object ({}), so the userInfo[0] in the first place (when there are no data fetched from the server) will be undefined and it will throw an error when you try to access its child. To solve this you can use optional chaining, whenever you try something like this.

So doing this will solve your issue:

const eventName = userInfo[0]?.eventName;

/* Whenever userInfo is undefined the eventName will
be set to undefined as well and it will prevent the
application from throwing an error when you try to
access userInfo child */
Related