Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

react native - How can I properly call this custom hook, and avoid infinite re-renders?

I'm using Apollo Client and wanted to make re-usable calls, so I was recommended to use Custom Hooks. I've tried but don't think I'm implementing them properly as they're re-rendering indefinitely and I can't figure out if this will actually do what I want.

I would like to, from another component, call useHandleFollow to call either useFollowUser or useUnfollowUser which will perform one of two useMutations, based on the isFollowingUser conditional.

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
}

I then tried to instantiate that like this, from the body of another component:

const followed = useHandleFollow({ user: author, isFollowingAuthor })

But that triggers an endless loop. Really, I want to only call this on a user's click, so have a function like this:

const handleUserFollow = (user) => {
  useHandleFollow(user, true)
}

How should I be going about this instead? Thank you in advance!

Edit: The proposed similar question is a different problem, this question is a separate issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...