How to change this promise returned function into an async await?

Viewed 29

Initially I write my code with promise based script .then().catch

But when I tried to change it into the async await function. Its not working anymore. Please someone help me with this.

My Old Code Which is working

export const fetchToken = (params) => {
    return (dispatch) => {
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };
        return axios
            .post(`/api/token`, params, config)
            .then((res) => {
                tokenData = res.data.access_token;
                dispatch({
                    type: LOGGED_IN,
                    payload: res.data,
                });
            })
            .catch((err) => {
                console.log(err);
                alert('Provided username and password is incorrect');
                throw err;
            });
    };
};

As you can see in the above code the function is returning a promise. But When I try to change it into async await

My simulator is give me Unexpected reserved work await Error

Here is my async await code in redux

export const fetchToken = async (params) => {
  return (dispatch) => {
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };
    try {
      const response = await axios.post(`/api/token`, params, config);
            const data = await response.json();
            tokenData = data.access_token
            dispatch({ type: LOGGED_IN, payload: res.data})
    } catch {
                console.log(err);
        alert('Provided username and password is incorrect');
        }
  };
};
1 Answers

Your async is applied to the wrong function, it should be on the dispatch function

export const fetchToken = (params) => (
  async (dispatch) => {
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };
    try {
      const response = await axios.post(`/api/token`, params, config);
            const data = await response.json();
            tokenData = data.access_token
            dispatch({ type: LOGGED_IN, payload: res.data})
    } catch {
                console.log(err);
        alert('Provided username and password is incorrect');
        }
  };
);

NB: I've removed the braces; arrow function return is implied https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Related