0

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.

FiFi
  • 79
  • 10
  • setter function for a state is async. If you want to log the state change, do this `useEffect(()=>{if(friendPosts.length>0)console.log(friendPosts)},[friendPosts])` – Inder May 04 '22 at 12:40
  • The dependency of friendPosts turns it to an infinite loop – FiFi May 04 '22 at 12:43
  • Have you created another useEffect or just added the code in the one you already have? – Inder May 04 '22 at 12:45
  • The useEffect I added above, should be a new one – Inder May 04 '22 at 12:45

1 Answers1

2

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