Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

undefined is not an object , can't access the Api response

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel



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>
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading