Asynchronous resource with
Suspensesupports
yarn add @sphinx-software/resourceData = await Operation(Parameter)
In the traditional approach, the above equation is showing how we deal with async resources / data
Let's change the equation into a new form:
Resource = Operation()
Data = Resource.fetch(Parameter)
That's what library all about. It helps you defer the Operation and its Parameters 👌
Let's declare an Operation called GET_PROFILE
// The operations.tsx fileimport{Operation}from'@sphinx-software/resource'exporttypeUser={name: stringage: number}exporttypeUserSearchCondition={keyword: string}constwait=(ms: number)=>{returnnewPromise((resolve)=>{setTimeout(resolve,ms)})}exportconstGET_PROFILE: Operation<UserSearchCondition,User>={initial: {name: 'Lucy',age: 25},asyncexecute(condition){// TODO will call the real searching API with the given conditionconsole.log(condition)awaitwait(1000)return{name: 'Rikky',age: 30}}}An Operation needs at least one execute method with given parameters.
You can also define the default value of the resource by providing the initial property
Now, let's get the Resource with the newly created Operation
importReact,{Suspense}from'react'import{GET_PROFILE,User}from'./operations'import{useResource,Resource}from'@sphinx-software/resource'// ...constUserDetail=({ resource }: {resource: Resource<User>})=>{constuser=resource.fetch()return(<span>Hello {user.name}</span>)}constApp=()=>{const[userResource,execute]=useResource(GET_PROFILE)return(<div><buttononClick={()=>execute({keyword: 'rikky'})}>Load</button><Suspensefallback='Loading...'><UserDetailresource={userResource}/></Suspense></div>)}- Each time you press the
Loadbutton, the resource will be re-created. - Calling the
fetch()method will get the user data or - make theUserDetailcomponent suspended
Sometimes, you just need to read the execution state of the resource to update the
component based on it. You can call the useResourceState() hook for it.
// ...const{ error, loading, result }=useResourceState(userResource)We eventually want to cancel the operation while it is executing. In operation definition, we can archive it by registering the cancel callback.
exportconstWAIT: Operation<number,void>={execute(ms,onCancel){returnnewPromise((resolve)=>{consttimeout=setTimeout(()=>resolve(),ms)onCancel(()=>{clearTimeout(timeout)})})}}///exportdefault()=>{const[waitingResource,fetch]=useResource(WAIT)return(<div><buttononClick={()=>fetch()}>Wait for it</button><buttononClick={()=>waitingResource.cancel()}>Cancel</button></div>)}You can pass an error or error message into the cancel() method.
The fetch() will throw the given error.
If you there are no error message provided, the resource will continue to suspended.
That's it! Happy coding! ❤️
MIT © monkey-programmer