i have a problem when trying to use the api response in my components , I fetched the api stores the response correctly but when accessing the response object I get this error
undefined is not an object (evaluating ‘response.employee_name’)
here is my code :
export default function TutorsScreen ({ navigation }) {
let [response ,setResponse] =useState();
useEffect(() => {
fetch("https://dummy.restapiexample.com/api/v1/employee/1")
.then(res => res.json())
.then((jsoon)=>setResponse(jsoon.data)) },[]);
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text
onPress={() => navigation.navigate('Home')}
style={{ fontSize: 26, fontWeight: 'bold' }}>
employee salary: {response.employee_salary} </Text>
</View>
)
}
>Solution :
SOLUTION 1
You should set intital state as {} empty object to response as:
let [response, setResponse] = useState({});
Because you are accessing it in JSX as:
{response.employee_salary}
Initial value is undefined. So your response is undefined and you can’t access property from undefined
SOLUTION 2
You can also use optional chaining as:
{response?.employee_salary}
SOLUTION 3
You can only render Text if response is truthy value i.e not undefined (in your case)
{
response && (
<Text
onPress={() => navigation.navigate('Home')}
style={{ fontSize: 26, fontWeight: 'bold' }}
>
employee salary: {response.employee_salary}
</Text>
)
}