0
votes

I am working on a Instagram clone project. I am doing the profile page part and got some problems. I am trying to use hooks (useState) to set my response from the server with the user document. My problem is that when I use the useEffect (only once with []), the username state is not set. I let useEffect run infinitely, and I found out that the state is set after some little time.

    const getUser = async () => {
        await axios.get(`/user/getbyusername/${props.match.params.username}`)
            .then(res => {
                console.log(res.data) // PRINTS DATA CORRECTLY
                setProfileUser({
                    _id: res.data._id,
                    username: res.data.username,
                    fullName: res.data.fullName,
                    followersCount: res.data.followersCount,
                    followingCount: res.data.followingCount,
                    profileImage_PublicId: res.data.profileImage_PublicId,
                    bio: res.data.bio
                })
                console.log(profileUser)
            })
    }
    // DOES NOT SET ANY DATA
    useEffect(() => {
        getUser(); // async function and awaits for the server response

        // HERE, I call getUserPosts using profileUser._id, and it profileUser._id is not set yet
        getPosts(); // async function as well
    }, [])

Checking if setProfileUser(...) is correct, and it is because it sets the data, but after some time even though I could console.log(res.data) in the correct first time using [].

    // WORKS, sets the user state after two runs. NOT GOOD PRACTICE
    useEffect(() => {
        getUser();
    })
1

1 Answers

2
votes

Add another useEffect hook that runs when profileUser changes, so that it runs after setProfileUser finishes:

useEffect(getUser, []);
useEffect(() => {
    if (profileUser) {
      getPosts();
    }
  },
  [profileUser],
);