Using async/await inside a React functional component

You will have to make sure two things

  • useEffect is similar to componentDidMount and componentDidUpdate, so if you use setState here then you need to restrict the code execution at some point when used as componentDidUpdate 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
  );
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)