Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  126] [ 7]  / answers: 1 / hits: 6940  / 3 Years ago, thu, june 24, 2021, 12:00:00

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.


More From » reactjs

 Answers
3

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);

[#1185] Friday, June 18, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;