0

I am new to the web development. I am using react.js.So, Here I want to use the async/awaitfor the API call. I am using axios.

Now,

what I have is like

export function fetchToken(bodyjson) {
  return (dispatch) => {
    let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
    return post(url, bodyjson)
      .then((response) => {
        if (response.status === 200) {
          localStorage.setItem('user', bodyjson.userName);
          localStorage.setItem('access_token', response.payload.access_token);
          history.push('/');
          dispatch({
            type: LOGIN_SUCCESS,
            data: response.payload,
          })
        }
        else {
          dispatch({
            type: LOGIN_FAILED,
            data: response.status,
          });
        }
      })
  }
}

and my post service is like,

export const post = (url, post_data) =>
    axios.post(
        apiGatewayEndpoint.apiGatewayEndpoint + url,
        post_data,
        {
            headers: {
                "Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null,
                "Content-Type": "application/json"
            }
        }
    ).then(data => {
        if (data.status === HttpStatus.OK) {
            return {
                status: data.status,
                payload: data.data
            };
        }
    }).catch(err => {
        return {
            status: err.response.data,
            payload: null
        };
    });

Now, I want to use the async await over here. I am very confused between this. I have gone through lots of the tutorials. I want to call an API immediately after the login. on that basis I want to redirect user to the diff pages.

So, can any one help me with this async-await

THANKS:-)

Now I am using it like,

export function fetchToken(bodyjson) {
  return async (dispatch) => {
    let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
    let response = await post(url, bodyjson)
    if (response.status === 200) {
      localStorage.setItem('user', bodyjson.userName);
      localStorage.setItem('access_token', response.payload.access_token);
      let fetchJd = FETCH_JD_ROOT_URL + page + "&" + size;
      let newApiResponse = await get(fetchJd)
      if (newApiResponse.status === 200) {
        dispatch({
          type: LOGIN_SUCCESS,
          data: response.payload,
        })
        dispatch(sendUserJd(newApiResponse.payload));
      }else {
    dispatch({
      type: LOGIN_FAILED,
      data: response.status,
    });
  }

    }
    else {
      dispatch({
        type: LOGIN_FAILED,
        data: response.status,
      });
    }
  }
1

2 Answers 2

2

for get requests, you can use params to send data etc etc.

   export const getData = async () => {
    try {
        const { data } = await axios({
            method: 'get', //you can set what request you want to be
            url: `yoururl`,
            params: {
            // key values pairs   
            }
            headers: {
                'token': token
            }
        });
        // run some validation before returning
        return data;
    } catch (e) {
        console.log(e);
        return .. some error object;
    }
};

for post request

export const getData = async (params) => {
    try {
        const { data } = await axios({
            method: 'post', //you can set what request you want to be
            url: `url`,
            data: params,
            headers: {
                'x-auth-Token': token
            }
        });
        // run some validation before returning
        return data;
    } catch (e) {
        console.log(e);
        return .. some error object;
    }
};

error object example

{
  status: 'error',
  message: 'failed with something'
}

then you can call any api like this,

async componentDidMount() {
 const data = await getData();
 if(data.status === 'Something') {
// do something    
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

So, I should replace the post call with this ?
I want to call an api immediately after the login success
yeah you can do it, if you want to call after login... and i hope when you do all your calls in async await, you just need to call login api first, like await login(), then call other api like await getSomething() and so on. makes your api's reusable and readable
1

You dont exactly need async await for this purpose.

With then chain approach

export function fetchToken(bodyjson) {
    return (dispatch) => {
        let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
        return post(url, bodyjson)
        .then((response) => {
            if (response.status === 200) {
                localStorage.setItem('user', bodyjson.userName);
                localStorage.setItem('access_token', response.payload.access_token);
                history.push('/');
                dispatch({
                    type: LOGIN_SUCCESS,
                    data: response.payload,
                })
                //next api call
                return post(newUrl, newBodyjson)
            }
            else {
                dispatch({
                    type: LOGIN_FAILED,
                    data: response.status,
                });
            }
        })
        .then((newApiResponse) => {
            //Do stuffs with new api response
        })
    }
}

But if you want to use async-await approach only

export function fetchToken(bodyjson) {
    return async (dispatch) => {
        let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
        let response = await post(url, bodyjson)
        if (response.status === 200) {
                localStorage.setItem('user', bodyjson.userName);
                localStorage.setItem('access_token', response.payload.access_token);
                history.push('/');
                dispatch({
                    type: LOGIN_SUCCESS,
                    data: response.payload,
                })
                let newApiResponse = await post(newUrl, newBodyjson)
                //Do stuffs with new api response
            }
            else {
                dispatch({
                    type: LOGIN_FAILED,
                    data: response.status,
                });
            }
    }
}

8 Comments

you can add one catch block at the end of all .then, and handle errors there
Hey, I have used your way. here what is happening is when I click on login that time it gives response and I dispatch that so because of that it changes props immediately but till that time the second request has not yet given response. So, How should I handle this, that before dispatching the response of first request, Should I send the response of this two requests in the newapi call itself?>
depending on your need you change where you want to dispatch. As per issue I think you should dispatch in the new api then block i.e. after making new call
I am sorry I asking you one more question. Now, I am totally new so , Now if first api call is success but the second api call gets failed, and In that api call only I am redirecting user to some another page so, In this case what should I do ? and I have used async await I have updated in the question please take a look
should I handle the errors in the else part of that request ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.