Search code examples
reactjsfetch-api

Fetching data but "Cannot read property '0' of undefined"


I try to fetch some data from the https://randomuser.me/api/ . I wanna take an random user gender but i don't know why my function doesn't do it and i get this error "Cannot read property '0' of undefined"

My code:

const [fetchData, setFetchData] = useState('');
         
    fetch('https://randomuser.me/api/')
        .then((response) => response.json())
        .then(setFetchData)
        .then(console.log(fetchData.results[0].gender));

Solution

  • fetchData doesn't get updated when setFetchData is called. Remember, it's just a local variable that got assigned when you invoked useState. It doesn't magically get updated until the next call to your function. And even then, setState is asynchronous, so it might not change immediately.

    This is what you likely really want.

    fetch('https://randomuser.me/api/')
        .then((response) => response.json())
        .then((json)=> {
             setFetchData(json);
             console.log(json.results[0].gender);
         });
    

    I tried it out locally and it worked for me.

    Also, as an aside. For robustness, so you don't throw an exception on a console statement when the response is completely unexpected:

    if (json && json.results && json.results[0]) {
        console.log(json.results[0].gender);
    }