Skip to content

Instantly share code, notes, and snippets.

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