I have a problem with the feth of a JSON, I'm getting a JSON from google maps (this is the code) but I find it undefined.
const [isLoading, setLoading] = useState(false);
const [info, setInfo] = useState([]);
const getInfo = () => {
fetch(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?place_id=${resturant.id}&$"'privatekey'"`)
.then((response) => response.json())
.then((json) => setInfo(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}
useEffect(() => {
setLoading(true);
getInfo();
}, []);
return(
<View style={style.card}>
{
isLoading ? <Text>LOADING</Text> :
<View style={{
flexDirection: "row",
justifyContent: "space-between",
marginTop: 10
}}>
<Text style={{fontSize: 16, fontWeight: "bold"}}>{resturant.nome}</Text>
<Text style={{fontSize: 16, fontWeight: "bold"}}>{resturant.id}</Text>
<Text>{info.result.name}</Text> //this is the problem
</View>
}
</View>
)
Thanks
CodePudding user response:
const [isLoading, setLoading] = useState(false);
const [info, setInfo] = useState([]);
const getInfo = () => {
fetch(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?place_id=${resturant.id}&$"'privatekey'"`)
.then((response) => response.json())
.then((json) => setInfo(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}
useEffect(() => {
setLoading(true);
getInfo();
}, []);
return(
<View style={style.card}>
{
isLoading ? <Text>LOADING</Text> :
<View style={{
flexDirection: "row",
justifyContent: "space-between",
marginTop: 10
}}>
<Text style={{fontSize: 16, fontWeight: "bold"}}>{resturant.nome}</Text>
<Text style={{fontSize: 16, fontWeight: "bold"}}>{resturant.id}</Text>
<Text>{info?.result?.name}</Text> //Update to utilize optional chaining
</View>
}
</View>
)
I am assuming the some of the objects do not contain the same level of information. Because of this, opt to use optional chaining to account for some of your result objects either missing or not containing a name like I am doing above.
EDIT
instead of optional chaining you could also update your initial state of your isLoading state to be true initially, there is no reason for it to be initially false. This will in turn ensure that your JSX will not render the info.result.name until the fetch request is completed.