Using async/await inside a React functional component
You will have to make sure two things
useEffect
is similar tocomponentDidMount
andcomponentDidUpdate
, so if you usesetState
here then you need to restrict the code execution at some point when used ascomponentDidUpdate
as shown below:
function Dashboard() {
const [token, setToken] = useState('');
useEffect(() => {
// React advises to declare the async function directly inside useEffect
async function getToken() {
const headers = {
Authorization: authProps.idToken // using Cognito authorizer
};
const response = await axios.post(
"https://MY_ENDPOINT.execute-api.us-east-1.amazonaws.com/v1/",
API_GATEWAY_POST_PAYLOAD_TEMPLATE,
{ headers }
);
const data = await response.json();
setToken(data.access_token);
};
// You need to restrict it at some point
// This is just dummy code and should be replaced by actual
if (!token) {
getToken();
}
}, []);
return (
... rest of the functional component's code
);
}
With React Hooks, you can now achieve the same thing as Class component in functional component now.
import { useState, useEffect } from 'react';
const Dashboard = props => {
const classes = useStyles();
const [token, setToken] = useState(null);
useEffect(() => {
async function getToken() {
const token = await fetchKey(props.auth);
setToken(token);
}
getToken();
}, [])
return (
... rest of the functional component's code
// Remember to handle the first render when token is null
Also take a look at this: Using Async await in react component