user3403614 user3403614 - 1 month ago 15
Ajax Question

Where is the best place to run Ajax call function inside Reactjs?

I am working on Reactjs web app with Redux.

So for now i run Ajax call inside my components like this.

componentDidMount(){
const props = this.props;
const deafaultUrl = apiUrl['development'];

$.ajax({
url: deafaultUrl + '/v1/movies/top_rated_homepage',
dataType: 'json',
contentType: 'application/json',
success: function(data) {
return props.update_homepage_best_movie_data(data);
},
error: function(xhr, status, err) {
console.error(status, err.toString());
return {}
}
});
}


And it works fine for now.
But after i read the redux document, they suggest to send the request inside the action.js file like this.

import fetch from 'isomorphic-fetch'

export const REQUEST_POSTS = 'REQUEST_POSTS'
function requestPosts(subreddit) {
return {
type: REQUEST_POSTS,
subreddit
}
}

export const RECEIVE_POSTS = 'RECEIVE_POSTS'
function receivePosts(subreddit, json) {
return {
type: RECEIVE_POSTS,
subreddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
}
}

export function fetchPosts(subreddit) {

return function (dispatch) {

dispatch(requestPosts(subreddit))

return fetch(`http://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json =>

dispatch(receivePosts(subreddit, json))
)

}
}


What is the pros/cons between this two method?

Thanks!

Answer

The second is the recommended way.

Redux is built based on the Flux architecture. This follows the following pattern Flux

The Web API is the place where you need to place all your API calls. The reason for this is, when you export each API as an action, it can be used across n number of components.

For example, if you place a AJAX call inside a component <App/> and if you want to use the same AJAX call in other component <Menu/>, it is not possible with your earlier approach. But, when you export each AJAX call as an action, those actions will be available across all the components and can be use.

The Pros:

  1. Increases re-usability
  2. Abstracts the APIs from the view.
  3. Better code maintenance
  4. Easy to debug.

The Cons:

  1. Disturbs the FLUX pattern
  2. Reduces re-usability
  3. Redundant code
  4. Very difficult to scale.

Hope this helps.

Comments