Reputation: 4177
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!
Upvotes: 0
Views: 96
Reputation: 19113
The second is the recommended way.
Redux is built based on the Flux architecture. This follows the following pattern
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:
The Cons:
Hope this helps.
Upvotes: 1