Updating the Profile component

In the Profile view, FollowProfileButton should only be shown when the user views the profile of other users, so we need to modify the condition for showing the Edit and Delete buttons when viewing a profile, as follows:

{auth.isAuthenticated().user && 
auth.isAuthenticated().user._id == values.user._id
? (edit and delete buttons)
: (follow button)
}

In the Profile component, after the user data is successfully fetched in useEffect, we will check whether the signed-in user is already following the user in the profile or not and set the following value to the respective state, as shown in the following code.

mern-social/client/user/Profile.js:

let following = checkFollow(data)
setValues({...values, user: data, following: following})

To determine the value to set in following, the checkFollow method will check if the signed-in user exists in the fetched user's followers list, then return match if found; otherwise, it will return undefined if a match is not found. The checkFollow method is defined as follows.

mern-social/client/user/Profile.js:

const checkFollow = (user) => {
const match = user.followers.some((follower)=> {
return follower._id == jwt.user._id
})
return match
}

The Profile component will also define the click handler for FollowProfileButton so that the state of the Profile can be updated when the follow or unfollow action completes, as shown in the following code.

mern-social/client/user/Profile.js:

  const clickFollowButton = (callApi) => {
callApi({
userId: jwt.user._id
}, {
t: jwt.token
}, values.user._id).then((data) => {
if (data.error) {
setValues({...values, error: data.error})
} else {
setValues({...values, user: data, following: !values.following})
}
})
}

The click handler definition takes the fetch API call as a parameter and is passed as a prop to FollowProfileButton, along with the following value when it is added to the Profile view, as follows.

mern-social/client/user/Profile.js:

<FollowProfileButton following={this.state.following} onButtonClick={this.clickFollowButton}/>

This will load FollowProfileButton into the profile view, with all the necessary conditions accounted for, and provide the current user the option to follow or unfollow other users in the MERN Social application. Next, we will extend this feature to allow users to view the list of followings or followers in the user profile view.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset