I'm currently using Apollo Client's useQuery and useMutation hooks to perform the same function in several different components. Instead of repeating the logic, I would like to create a helper function that can keep the logic in a single place.
The problem with this, is useQuery and useMutation being hooks mean they can't just live in a separate file as functions, but instead need to be valid React function components.
I started trying to make something functional but starting to think this might not be able to be done.
export function HandleFollow (props) {
const [useFollowUser, { followedData, followError }] = useMutation(FOLLOW_USER);
useFollowUser({ variables: { fromId: auth().currentUser.uid, toId: "userIDxyz"}, onCompleted: props.handleUserFollow(user, isFollowingAuthor)})
}
Is it possible to use util/helper functions with React Hooks? Thanks in advance!
When creating the below, I'm receiving "Invalid hook call. Hooks can only be called inside of the body of a function component." and I can't figure out why.
I think that may be due to calling this from inside a function, but I can't figure out how to avoid that.
export function useHandleFollow(props) {
const { user, isFollowingUser } = props
const [useFollowUser, { followedData, followError }] = useMutation(FOLLOW_USER);
const [useUnfollowUser, { unfollowedData, unfollowedError }] = useMutation(UNFOLLOW_USER);
const [followSuccess, setFollowSuccess] = useState(false)
if(!isFollowingUser){
useFollowUser({ variables: { fromId: auth().currentUser.uid, toId: user.id}, onCompleted: setFollowSuccess(true)})
}else{
useUnfollowUser({ variables: { fromId: auth().currentUser.uid, toId: user.id}, onCompleted: setFollowSuccess(true)})
}
return followSuccess
}
And when I call this right away in my component (instead of calling from inside a function), it continues to infinitely re-render:
Here's some more complete code from the component
in Home.js:
const followed = useHandleFollow({ user: author, isFollowingAuthor })
export default posts = (props) =>{
let { post, excludeUser = false } = props
let { author } = post
let { date, things, isFollowingAuthor } = post
let { profile_picture } = author
let currentUser = auth().currentUser
const [followed] = useHandleFollow({ user: author, isFollowingAuthor })
return ()
}
And this is in follow.js, which I'm importing as import { useHandleFollow } from...
export function useHandleFollow(props) {
const { user, isFollowingUser } = props
const [followUser, { followedData, followError }] = useMutation(FOLLOW_USER);
const [unfollowUser, { unfollowedData, unfollowedError }] = useMutation(UNFOLLOW_USER);
const [followSuccess, setFollowSuccess] = useState(false)
if(!isFollowingUser){
followUser({ variables: { fromId: auth().currentUser.uid, toId: user.id}, onCompleted: () => setFollowSuccess(true)})
}else{
unfollowUser({ variables: { fromId: auth().currentUser.uid, toId: user.id}, onCompleted: () => setFollowSuccess(true)})
}
return [followSuccess]
}