I’m writing React JS web application and i have this code:
import React,{useEffect,useState} from 'react'
import {useParams} from 'react-router-dom'
import {Card} from 'react-bootstrap'
import {MapContainer, TileLayer, Market} from 'react-leaflet'
const Restaurant=()=>{
const {id}=useParams();
const [restaurant,setRestaurant]=useState([]);
const [loading,setLoading]=useState(true);
const url=`http://localhost:8080/api/restaurants/${id}`;
useEffect(()=>{
setLoading(true);
fetch(url)
.then(data=>data.json())
.then(res=>{
if(res.hasOwnProperty('_id'))
setRestaurant(res);
else
setRestaurant([]);
console.log(res);
})
.catch((err)=>console.log('There was an error',err));
setLoading(false);
},[id, url]);
return(
//id in params
// <p>Restaurant id:{id}</p>
<>
<Card>
<Card.Body>
<Card.Title>{restaurant.name}
</Card.Title>
<Card.Text>{restaurant.address.building+' '+ restaurant.address.street}</Card.Text>
</Card.Body>
</Card>
</>
)
}
export default Restaurant;
After the fetch I get the Object with restaurants and save it to the restaurant hook using setRestaurant.
But for some reason, {restaurant.name
} works fine, but {restaurant.address.building+' '+ restaurant.address.street}
does not work and it says cannot read properties of undefined.
Can someone please help me solve this issue?