UseState state no longer updating after switching state quickly

Viewed 36

I have built the following component. When I use this component and change the userid (rather quickly) from the parent component, then at some point the user gets stuck and no longer updates for certain userids - either the one I switched from or switched to, not sure. For others it does update but I'm not sure if for all others.

interface SingleUserOverviewProps {
  userId: string
}

function SingleUserOverview({ userId }: SingleUserOverviewProps) {
  const [user, setUser] = useState<UserOverviewProps>()
  
  const { data, loading, error } = useUserQuery({
    variables: { userId: userId },
    onCompleted: (data) => {
      if (data.user) {
        setUser(data.user)
      }
    },
  })

  return (
    <>
      {user ? (<div>user.name</div>) : null}
    </>
  )
}

If I don't make the state and just assign the user as

const user = data.user

Then I don't get this problem. I would however like to be able to implement a button which performs an update to the user on the backend and then re-renders the component with the new data - hence I thought using useState is necessary.

1 Answers

(expecting the parent's userId to be a state) =>

you can use refetch inside an useEffect where userId changes:

const { data, loading, error ... refetch } = useUserQuery(...
...
useEffect(() => {
   refetch();
},[userId]);
...

or maybe you can use useLazyQuery with a useEffect:

interface SingleUserOverviewProps {
  userId: string
}
function SingleUserOverview({ userId }: SingleUserOverviewProps) {
  const [user, setUser] = useState<UserOverviewProps>()
  
  const [ callbackend ,{ data }] = useLazyQuery(SEARCH,{
    variables: { userId: userId },
    fetchPolicy: 'cache-and-network',
    onCompleted: (data) => {
      if (data.user) {
        setUser(data.user)
      }
    },
  })

    useEffect(() => {
        if(userId) {
            callbackend();
        }
    },[userId]);

  return (
    <>
      {user ? (<div>user.name</div>) : null}
    </>
  )
}
Related