javascript - Fetching data with redux actions -
i having issue internally how structure redux actions fetch data via rest api.
i fetching variety of data like
- all posts published
- a singular post
- all current users
- search results
i wondering if create action fetch's data each endpoint or if create singular fetch action fetches data supplied route?
current implementation:
function requestposts(site) { return { type: request_posts, site } function fetchposts(site) { return dispatch => { dispatch(requestposts(site)) return fetch(`http://notareallink.com/posts`) .then( response => response.json() ) .then( json => dispatch( receiveposts( site, json ) ) ) } function requestpost(site) { return { type: request_post, site } function fetchpost(site) { return dispatch => { dispatch(requestpost(site)) return fetch(`http://notareallink.com/post/post-id`) .then( response => response.json() ) .then( json => dispatch( receivepost( site, json ) ) ) } function requestusers(site) { return { type: request_users, site } function fetchusers(site) { return dispatch => { dispatch(requestusers(site)) return fetch(`http://notareallink.com/users`) .then( response => response.json() ) .then( json => dispatch( receiveusers( site, json ) ) ) }
to me feels load of duplicate code doing same thing (fetching data endpoint).
is correct way or should creating singular action data fetch , pass relevant route?
i sorry if not clear trying wrap head around type out.
all of functions can call functions handle repetative tasks w/o code duplication.
first of need extract repetative fetch
calls.
const callapi = url => fetch(`http://notareallink.com/${url}`).then(res => res.json())
to avoid repetative action dispatching can use middlewares. seems have thunk
middleware. can add own or use package.
const promisemiddleware = ({dispatch}) => next => action => { const {promise, pending, success, fail} = action if(promise) { dispatch(pending()); promise.then( res => dispatch(success(res)), err => dispatch(fail(err)) ) } return next(action) }
and use this
const requestposts = () => ({ type: request_posts }) const recieveposts = posts => ({ type: recieve_posts, posts }) const requestpostsfail = reason => ({ type: request_posts_fail, reason }) const fetchposts = () => dispatch => dispatch({ promise: callapi('posts'), pending: requestposts, success: receiveposts, fail: requestpostsfail })
Comments
Post a Comment