简体   繁体   中英

Better ways to handle REST API call in Redux

In my app, I need to call several REST API endpoints:

// The UI Class
class LoginForm extends Component {
    handleSubmit(){
        store.dispatch(login(username, password));
    }
}

// An action
function login(username, password){
    return dispatch => {
        fetch(LOGIN_API, {...})
        .then(response => {
            if (response.status >= 200 && response.status < 300){
                // success
            } else {
                // fail
            }
        })
    }
}

The gist is above and easy to understand. User triggers an action, an ajax call to the corresponding endpoint is made.

As I am adding more and more API endpoints, I end up with a bunch of functions similar to the skeleton of the login function above.

How should I structure my code in such a way that I don't repeat myself with duplicate ajax functions?

Thanks!

I strongly suggest you to read this popular github sample project. At first it is hard to understand but don't worry and continue to read and realize what is happening in that.

It uses very clear and simple way to handle all of your API calls. when you want to call an API, you should dispatch an action with specific structure like this:

{
    types: [LOADING, SUCCESS, FAIL],
    promise: (client) => client.post('/login', {
       data: {
               name: name
             }
    })
}

and it will handle these kind of actiona by a custom middleware .

The way I handle a similar situation is to have 2 wrapper for API calls:

function get(url) {
    return fetch(url)
        .then(response => {
            if(response.status >= 200 && response.status < 300) {
                return response
            }
            else {
                let error = new Error(response.statusText)
                error.response = response
                throw error
            }
        })
        .then(response=> response.json())
}

This wrapper will take a url and return the json data. Any error that happens (network, response error or parsing error) will be caught by the .catch of get

A call basically looks like that:

get(url)
    .then(data => dispatch(someAction(data)))
    .catch(error => dispatch(someErrorHandler(error)))

I also have a post wrapper that in addition sets the header for CSRF and cleans the data. I do not post it here as it is quite application-related but it should be quite ovious how to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM