Created
October 9, 2019 17:46
-
-
Save alonbardavid/c560770f449d3ddcbd39a25c62d3cd1c to your computer and use it in GitHub Desktop.
Why use mobx gist 9
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
const ResourceContext = React.createContext(); | |
function useResource(){ | |
const [resource,setResource] = React.useState({}); | |
return { | |
resource, | |
requestResource(){ | |
const interval = setInterval(()=>({ | |
// this is a contrived example for brevity, I know it's not | |
// how you'll do it and that it won't work since resource is | |
// always the original value | |
setResource({...resource,seconds:resource.time + 1 }) | |
}),1000) | |
setResource({loading:true,seconds:0}); | |
return fetch(`url/resource/${resourceId}`) | |
.then(response=>response.json()) | |
.then(json=>setResource({...resource,loading:false,resource:json})) | |
.catch(error=>setResource({loading:false,error})) | |
.finally(()=>clearInterval(interval)) | |
} | |
} | |
} | |
//resource-view.js | |
function ResourceView(props) { | |
return props.loading? <Loader/>:<ResourceItem resource={props.resource}/> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment