2

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!

2
  • Move the fetch function into a util function that accepts a URL as a parameter? :) Commented Apr 8, 2016 at 11:45
  • @Idiot211 I thought about but it will not work because the handling of the success status for each endpoint is different Commented Apr 10, 2016 at 3:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

To use your solution with my example, I will be putting get(..).then(...).catch(...) inside the handleSubmit() of the UI component?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.