Home > Net >  Empty data after using UseEffect ReactJs
Empty data after using UseEffect ReactJs

Time:08-03

I want to get news but i have an empty dictionary in the first render. My useEffect

const [news, setNews] = useState({});
const [page, setPage] = useState(1);
const [user, setUser] = useState({});

useEffect(() =>{
    const getNews = async() =>{
        const newsData = await httpClient.get(`/feed/${pk}/?page=${page.toString()}`)
        setNews(newsData.data);
        const userData = await httpClient.get('/profile/')
        setUser(userData)
    }
    getNews();
}, [page])

How can i get data in the first time render?

CodePudding user response:

because you have [page] in the dependency array - add hook for initial render:

const [page, setPage] = useState(0);

useEffect(() => setPage(1), [])

CodePudding user response:

You will always have your state what you initialize it as on first render, react won't wait until useEffect is finished before render since that would lock up the UI.

You need some sort of loading indicator while data is fetching, you can do this for example

const [loading, setLoading] = useState(true);
const [news, setNews] = useState({});
const [page, setPage] = useState(1);
const [user, setUser] = useState({});

useEffect(() =>{
    const getNews = async() =>{
        const newsData = await httpClient.get(`/feed/${pk}/?page=${page.toString()}`)
        setNews(newsData.data);
        const userData = await httpClient.get('/profile/')
        setUser(userData)
        setLoading(false)
    }
    setLoading(true)
    getNews();
}, [page])

if (loading) {
  return <>{"loading"}</>
}

change the return value to whatever you want, maybe you want to just return an empty <></> component so that when it first shows up it'll have all the data.

  • Related