Created
October 9, 2019 17:41
-
-
Save alonbardavid/adde39cc2b34c54ed8bf1a0e37a3c965 to your computer and use it in GitHub Desktop.
Why use mobx gist 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in actions.js | |
// these are action creators | |
export const requestResource= (resourceId)=>({ | |
type: 'REQUEST_RESOURCE', | |
resourceId | |
}) | |
export const requestResourceSuccess = (resourceId,payload)=>({ | |
type: 'REQUEST_RESOURCE_SUCCESS', | |
resourceId, | |
payload | |
}) | |
export const requestResourceFailure = (resourceId,error)=>({ | |
type: 'REQUEST_RESOURCE_FAILURE', | |
resourceId, | |
error | |
}) | |
export const fetchResource = resourceId => dispatch =>{ | |
dispatch(requestResource(resourceId)); | |
return fetch(`url/resource/${resourceId}`) | |
.then(response=>response.json()) | |
.then(json=>dispatch(requestResourceSuccess(resourceId,json))) | |
.catch(e=>dispatch(requestResourceFailure(resourceId,e))) | |
} | |
// in reducers.js | |
export default (state = {}, action) => { | |
switch (action.type) { | |
case 'REQUEST_RESOURCE': | |
return { | |
resources:{ | |
...state.resources, | |
[action.resourceId]: {loading:true} | |
} | |
} | |
case 'REQUEST_RESOURCE_SUCCESS': | |
return { | |
resources:{ | |
...state.resources, | |
[action.resourceId]: {loading:false,resource:action.payload} | |
} | |
} | |
case 'REQUEST_RESOURCE_FAILURE': | |
return { | |
resources:{ | |
...state, | |
[action.resourceId]: {loading:false,error:action.error} | |
} | |
} | |
default: | |
return state | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment