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(() => { // You need to restrict it at some point // This is just dummy code and should be replaced by actual if (!token) { getToken(); } }, []); const getToken = async () => { 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); }; 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
const token = fetchKey(props.auth);
This returns a promise. To get the data from it, this is one way to do it:
let token = null;fetchKey(props.auth).then(result => { console.log(result) token = result;}).catch(e => { console.log(e)})
Let me know if that works.
I recreated a similar example: https://codesandbox.io/embed/quiet-wood-bbygk