Reputation: 6160
In the example bellow I'm trying to create a simple login/authentication component with React and Redux Toolkit.
const Login = () => {
const dispatch = useDispatch();
const [login, { isLoading }] = useLoginMutation();
const [loginData, setLoginData] = useState({
email: '',
password: '',
});
const loginHandler = async () => {
try {
const result = await login({
email: loginData.email,
password: loginData.password,
}).unwrap();
const { token, userId } = result;
const { data } = await dispatch(
backendApi.endpoints.getUser.initiate({ token, userId })
);
dispatch(
setCredentials({
user: {
email: data.user.email,
id: data.user.id,
name: data.user.name,
type: data.user.type,
},
token,
})
);
} catch (err) {
console.log(err);
}
};
return (
<Space>
{isLoading ? (
<SpinnerIcon />
) : (
// setLoginData and loginHandler are set and used here
// Standard React code: Input onChange -> setLoginData / Submit button onClick -> loginHandler
// (nothing special, code shortened for the sake of readability)
<FormWithEmailPasswordInputsAndButton />
)}
</Space>
);
};
This works fine, the problem is that:
I want to make use of the isLoading
property on the getUser
query result object so that the <SpinnerIcon />
component will be visible until both requests are done.
As it is, the spinnerIcon
component is only shown during the login
API call because I'm not using React Hooks to call getUser
query therefore I don't have the isLoading
property from getUser
available to the rest of the component.
But if I want to use React Hooks to make the call I'll need the result from the login
mutation beforehand.
const [getUser, { isLoading: isUserLoading }] = useGetUserQuery(resultFromLoginMutation);
And I don't know how to do that. One after the other, so that I can make use of both isLoading
properties.
Upvotes: 4
Views: 9175
Reputation: 44086
You can use skipToken
or the skip
option:
const [login, { isLoading, data: resultFromLoginMutation, isSuccess }] = useLoginMutation();
const [getUser, { isLoading: isUserLoading }] = useGetUserQuery(resultFromLoginMutation, { skip: !isSuccess });
or
const [login, { isLoading, data: resultFromLoginMutation }] = useLoginMutation();
const [getUser, { isLoading: isUserLoading }] = useGetUserQuery(resultFromLoginMutation ?? skipToken);
Upvotes: 5