0
export function Login() {
  const [skip, setSkip] = useState(true);
  const { data, isFetching } = useVerifyUserQuery(userState, {
    skip,
  });

  const LoginButton = () => (
    <Button
      title="Login"
      onPress={() => {
        setSkip((prev) => !prev);
      }}
    />
  );

  return (
    …
  )
}

The requirement is to make a request when the button is pressed, and then store the returned data in a constant. Is there a good way to make sure data is returned before I store it.

Here is one of my solutions. Obviously it may cause some problems.

onPress={() => {
  setSkip((prev) => !prev);
  while(isFetching){}
  // save data
}}

And with the code below, storeData will be called multiple times.

export function Login() {
  const [skip, setSkip] = useState(true);
  const { data, isFetching } = useVerifyUserQuery(userState, {
    skip,
  });

  if (!isFetching && IsNotEmpty(data)){
    storeData();
  }
  const LoginButton = () => (
    <Button
      title="Login"
      onPress={() => {
        setSkip((prev) => !prev);
      }}
    />
  );

  return (
    …
  )
}
niuiic
  • 1
  • I think you really want to use a mutation here instead and then you can do away with all that magic you're trying to pull off here? – phry Mar 01 '22 at 16:51

1 Answers1

0

It looks like you just want to use the lazy version - useLazyVerifyUserQuery instead of common. It will be like:

export function Login() {
    const [ verifyUser ] = useLazyVerifyUserQuery();

    const handleLogin = async () => {
        const data = await verifyUser(userState).unwrap();
        // Probably you would want to use `storeData` somehow here?
    }

    const LoginButton = () => (
        <Button
          title="Login"
          onPress={handleLogin}
        />
    );

    return (
      ...
    )
}

PS: just a warning - using a nested component definition, like LoginButton inside Login - is a known antipattern that may cause significant performance issues.

Eugene Tusmenko
  • 836
  • 4
  • 11