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

Time:08-15

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>
)
}

CodePudding user response:

SOLUTION 1

You should set the initial state as {} empty object to response as:

let [response, setResponse] = useState({});

Because you are accessing it in JSX as:

{response.employee_salary}

The initial value is undefined. So your response is undefined and you can't access the 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>
    )
}

CodePudding user response:

Instead of setting the response to setResponse(jsoon.data),
Try : setResponse(jsoon.data.data)

useEffect(()  =>  {
    fetch("https://dummy.restapiexample.com/api/v1/employee/1")
    .then(res => res.json())
    // Set the function to setResponse(jsoon.data.data)
    .then((jsoon)=>setResponse(jsoon.data.data)) },[]);

You can see the sample API response to see why your method didn't work:

{"status":"success","data":{"id":1,"employee_name":"Tiger Nixon","employee_salary":320800,"employee_age":61,"profile_image":""},"message":"Successfully! Record has been fetched."}

CodePudding user response:

useEffect is starting working after first render docs so in first render this state is undefined. You can fix it in some ways

1.

{ response?.employee_salary }
{response?.employee_salary ?? 'Loading' }

or add loading state

export default function App({ navigation }) {
  let [response, setResponse] = useState();
  const [loading, setLoading] = useState(false);

  useEffect(async () => {
    const fetchData = async () => {
      fetch("https://dummy.restapiexample.com/api/v1/employee/1")
      .then((res) => res.json())
      .then((jsoon) => {
        setResponse(jsoon.data);
      });
    }

    setLoading(true);
    await fetchData();
    setLoading(false);
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div className="App">employee salary: {response?.employee_salary}</div>
  );
}
  • Related