I'm a new developer. If you login to our website, JWT will be created. When I press the button, I have to put it in the API as a backend. And if the screen is successful, the address in the API must be printed out. If it fails, 'authentication failure' should be displayed on the screen. I want to do this. Please help me.
import axios from 'axios';
import React, { useState } from 'react';
import { Button } from '@material-ui/core';
function TestPage() {
const onLogin = () => {
var variables = {
email: email,
password: password,
};
Axios.post('/auth/login', variables).then((res) => {
setCookie('token', res.payload.accessToken);
setCookie('exp', res.payload.accessTokenExpiresIn);
Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
Axios.get('/user/me').then((res) => {
console.log(res);
});
});
};
return (
<>
<div>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={(e) => customFetch(e)}>
address
</Button>
</div>
{address && <div>{address}</div>}
</>
);
}
export default TestPage;
CodePudding user response:
Generally for any network operation, it's helpful to know when it's in progress, has finished, and/or has an error. Let's set this up:
const [isLoading, setIsLoading] = useState(false)
const [data, setData] = useState(null)
const [error, setError] = useState(null)
// inside your `onLogin` function...
setIsLoading(true);
Axios.post('/auth/login', variables).then((res) => {
setCookie('token', res.payload.accessToken);
setCookie('exp', res.payload.accessTokenExpiresIn);
Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
// bit messy using the same error state for both but you can always refactor
Axios.get('/user/me').then((res) => {
console.log(res);
setData(res); // not sure where the actual data is with Axios
}).catch(err => setError(err);
}).catch(err => setError(err));
setIsLoading(false);
During your POST, set the state variables accordingly:
- Before the post,
setIsLoading(true)
- On success,
setData(response.data) // whatever your payload might be
- On error/failure,
setError(error)
Now in your component return, you can conditionally render your different states, e.g:
// your component body
if (isLoading) return (
// a loading state
)
if (error) return (
// an error state
// e.g. "Authentication Failure"
)
return (
// your success/ideal state
// e.g:
<>
<div>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={(e) => customFetch(e)}>
address
</Button>
</div>
{address && <div>{address}</div>}
</>
)
Alternatively, you could leverage the variables slightly differently:
return (
<>
<div>
<Button
variant="contained"
color="primary"
style={{ width: '200px' }}
onClick={(e) => customFetch(e)}
disabled={isLoading}>
address
</Button>
</div>
<div>
{isLoading
? 'Checking...'
: error !== null
? 'Something went wrong'
: 'Ready to submit'}
</div>
</>
)
The ternary style can be a bit messy though.