Skip to content

Instantly share code, notes, and snippets.

@alonbardavid
Created October 9, 2019 17:41
Show Gist options
  • Save alonbardavid/adde39cc2b34c54ed8bf1a0e37a3c965 to your computer and use it in GitHub Desktop.
Save alonbardavid/adde39cc2b34c54ed8bf1a0e37a3c965 to your computer and use it in GitHub Desktop.
Why use mobx gist 1
// 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