TypeError: Cannot read properties of undefined (reading 'building')

Hi guys, currently I am following the Restaurant Review tutorial by freecodecamp, may I ask why did I get this error:

TypeError: Cannot read properties of undefined (reading ‘building’)

I really have no idea why does the line restaurant.address.building does not work, but I have tried the following steps:

  1. I have checked the line of code , already declared in const [restaurant, setRestaurant] = useState(initialRestaurantState);
  2. I have tried to declare address with building, street and zipcode, but still doesn’t work.
    Below is my code
import React, { useState, useEffect } from "react";
import RestaurantDataService from "../services/restaurant";
import { Link } from "react-router-dom";


let Restaurant = props => {
  const initialRestaurantState = {
    id: null,
    name: "",
    address: {
      building: "",
      street: "",
      zipcode: 0,
    },
    cuisine: "",
    reviews: []
  };
  const [restaurant, setRestaurant] = useState(initialRestaurantState);

  const getRestaurant = id => {
    RestaurantDataService.get(id)
      .then(response => {
        setRestaurant(response.data);
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  };

  useEffect(() => {
    getRestaurant(props.match.params.id);
  }, [props.match.params.id]);

return(
   <div>
        {restaurant ? (
             <strong> Address: </strong> {restaurant.address.building} {restaurant.address.street}, {restaurant.address.zipcode}})
    </div>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.