Someone Special
Someone Special

Reputation: 13598

ReactJs Promise + Ajax Return Value

I have a function which uses jquery to call API and get a result. My API end is programmed to return the number "19" just for testing.

export function clientAdd(data) {
    return (dispatch) => {
        return $.ajax({
            url: "http://api.example.com/client/add/",
            headers: {'AUTHORIZATION': `${sessionStorage.jwt}`},
            type: 'POST',
            cache: false,
            data: data,
            dataType: 'json',
            success: function (data) {
                let redirectUrl = '/client/' + data
                return redirectUrl';

            },
            error: function(xhr, status, err)  {

                if (xhr.status === 401) {
                    sessionStorage.removeItem('jwt');
                    return '/signin';

                }
                console.log('xhr',xhr.responseText);
                console.log('status',status);
                console.log('err',err);
                return dispatch({type: GET_CLIENT_FAIL, err});
            }
        })
    }

}

Then in my component, upon clicking on the submit button, it will call the onSave function as follows

  onSave(event) {
    //event.preventDefault();
    this.props.actions.clientAdd(this.state.credentials).then((result) => {
        return this.setState({redirect: true, newCustomerId: result})

    }).catch((result) => {
        return this.setState({redirect: false, errorMessage: result})
    });
  }

Where the result is supposed to be the redirectUrl or ErrorMessage.

However, I'm keep getting the number 19 which is returned by my API.

I read online if I want to use promise in my component, i have to add return infront of $.ajax, if not "then" will be undefined.

Upvotes: 3

Views: 1522

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58613

What you can do is, create your own promise and put the ajax call inside it

Then call resolve and pass data that you want when then is called

resolve(data_passed_to_then)

Like this :

return new Promise((resolve,reject) => {
    $.ajax({
            ...
            success: function (data) {
                let redirectUrl = '/client/' + data
                resolve(redirectUrl);
            },
            error: function(xhr, status, err)  {
                ...
                // return dispatch({type: GET_CLIENT_FAIL, err});
                reject(err);
            }
        })
})

Upvotes: 4

Related Questions