File size: 1,330 Bytes
f5071ca |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/auth';
import { updateProfileData } from '../lib/api';
import { setLoginAlert } from '../store/loginAlert';
const useFollowUser = (profileData, userId) => {
const user = useAuth();
const navigate = useNavigate();
const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const handleClickFollow = () => {
if (!user) {
dispatch(setLoginAlert(true));
return;
}
if (profileData?.id === userId) {
navigate('/customize-profile');
} else {
setLoading(true);
const followers = profileData.followers || [];
const transformedFollowers = followers.includes(userId)
? followers.filter((id) => id !== userId)
: [...followers, userId];
updateProfileData({ followers: transformedFollowers }, profileData.id)
.then((_) => {
setLoading(false);
// console.log('followed');
})
.catch((err) => {
setLoading(false);
console.log(err);
});
}
};
return { handleClickFollow, loading };
};
export default useFollowUser;
|