Search code examples
javascriptreactjsreact-hooksmern

React setState returning empty result from server, when the result gets received successfully


I have the code as follows:

const [pageNumber, setPageNumber] = useState(1);
useEffect(() => {
    const readDashboardPosts = async () => {
        let limit = 4;
        try {
            const res = await axios.post( );
            setFriendPosts(res.data.posts);
            console.log('pos', res.data.posts);
        } catch (err) {
            console.error(err)
        }
    }
    readDashboardPosts();
    console.log('friend-posts from state: ', friendPosts);
}, [])

On first render, my console.log are as follows:

pos (4) [{…}, {…}, {…}, {…}]
friend-posts from state:  []

So, I did get the results from server successfully, since console.log of 'pos' is working but after I set state, it's not working properly as I get empty array although I am using async await. I also tried this with useCallback, but no luck.


Solution

  • first of all , setState is asynchronous

    second , to see if the state is set successfully either use React Devtools Go to Components and inspect your component

    Or try using useeffect like this :

    useEffect(()=>{
        console.log('friend-posts from state: ', friendPosts);
    
    
    } ,[friendPosts])