简体   繁体   中英

reactjs data.length accessible on save but not when browser refresh

I don't get it, in console I see my api data(array of 10 objects) but if I access the "data.data.length" when I save the file, it works(show number: 10 in console) but when I refresh the browser, the error occur(Uncaught TypeError: Cannot read property 'length' of undefined).

Also I found out that when my page refresh, it console.log "undefined" first then my array of 10 objects api data.....

I am so lost, what am I doing wrong?

import React, { useState, useEffect } from 'react';
import '../App.css';
import axios from 'axios';

function App() {
    const [data, setData] = useState({});

    useEffect(() => {
        axios
            .get(
                'http://api.giphy.com/v1/gifs/search?q=cat&limit=10&api_key=1234567890'
            )
            .then(({ data }) => {
                setData(data);
            })
            .catch((error) => {
                console.log(error);
            });
    }, []);

    return (
        <>
      {console.log(data.data)}
        </>
    );
}

export default App;

In the beginning of your component execution you have

const [data, setData] = useState({});

this is the first data you are using and this data is an empty object thats why data.data is undefined

Then your effect is executed and only after that data is updated in success case and remains the same in error(catch) state

So in case you want to use next code

data.data.length
// you are calling something like
// data.undefined.length

which in your case is throws exactly what it suppose to throw - Uncaught TypeError: Cannot read property 'length' of undefined

I would suggest you to use next piece of code if you like to use length

const length = data?.data?.length;

read more here Optional Chaining

As the second option you can set starting state as

const [data, setData] = useState({data:[]})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM