Reputation: 223
I keep this error Undefined is not an object(evaluating ....), I find it funny, because I get the object when i make a correction and it refreshes, but when i open a app at first, i get the error, So i delete the part that has the error then the app loads, i then bring back the delete part, it will show correctly. Please help, Im just learning react.
Im not sure but i think there is a method that makes my app wait when it fetches the data, then its loads, rather than just load at first nonetheless...
This is my code please.
function ExploreScreen() {
const getListingsApi = useApi(client.get(endpoint));
useEffect(() => {
getListingsApi.request();
}, []);
return ({getListingsApi && <Text>{getListingsApi.data[0].latitude}</Text>}) -this is the part i delete and bring back to ake it display.
I removed the parts that are working. This is just a brief version of the code, below is my useAPI hook
import { useState } from "react";
export default useApi = (apiFunc) => {
const [data, setData] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const request = async (...args) => {
setLoading(true);
const response = await apiFunc(...args);
setLoading(false);
setError(!response.ok);
setData(response.data);
return response;
};
return { data, error, loading, request };
};
Upvotes: 0
Views: 106
Reputation: 2020
It's hard without a reproducible example, but I would guess that data[0]
might be the culprit:
return ({getListingsApi && <Text>{getListingsApi.data[0].latitude}</Text>})
The collection is being initialized to []
(in the hook via const [data, setData] = useState([]);
) which means it won't have a first element.
This would explain why adding it later, would not cause an exception, since at that point, the data will already be loaded and the array will have been initialized.
Consider trying something like this:
return (
{getListingsApi && getListingsApi.data.length > 0 && (
<Text>{getListingsApi.data[0].latitude}</Text>
)}
)
Upvotes: 1