RFC: createResource/useResource
thysultan opened this issue · comments
This probably won't go into the first stable release with hooks, but is worth thinking about out-of-band non-the-less.
The idea is for a createResource/useResource
in parallel to createContext/useContext
for shared I/O state/dependencies.
An example of this might look like the following.
const TodoResource = createResource(data => fetch(`/get/data`))
function LeftPanel (props) {
const [resource, dispatch] = useResource(TodoResource)
return <button onClick={e => dispatch(e)}>Click Me</h1>
}
function RightPanel (props) {
const [resource, fetch] = useResource(TodoResource)
return <h1>{JSON.stringify(resource)}</h1>
}
function App () {
return (
<Suspense fallback="Loading...">
<LeftPanel/>
<RightPanel/>
</Suspense>
)
}
Where both LeftPanel
and RightPanel
can access a fetched and cached I/O resource using useResource
.
For the most part the React team is also planning to add something like this to React(search for createResource in the React repo).
What do we want to do about writing/updating I/O resources.
We can either assume 1. That I/O resources should be read only, in which case this API would just not deal with updates, or 2. That I/O resources should be read/write compatible.
For example with vanilla JavaScript you might implement some read/write mechanism with fetch
and friends.
Considering that, what should dispatch
in the aforementioned example do?
const TodoResource = createResource(data => fetch(`/api/get/`))
function LeftPanel (props) {
const [resource, dispatch] = useResource(TodoResource)
return <button onClick={e => dispatch(e)}>Click Me</h1>
}
- Nothing, there shouldn't be a dispatch.
- Re-fetch the resource?
- Post the resource.
- Post, and re-fetch the resource.
Where option 3-4 might see us update the example TodoResource
implementation to the following:
const TodoResource = createResource(data => fetch(`/api/get/`), data => fetch('api/post/', {
method: 'POST',
headers: {'accept': 'application/json', 'content-Type': 'application/json'},
body: JSON.stringify(data)
}))
React link: reactjs/rfcs#106
An existing implementation: https://github.com/schettino/react-request-hook
When is the resource fetched? Within a useEffect
or does this hook run server-side too?
I don't think read/write makes sense at the hook level, the resource itself should afford the interface.
Like Dyo.lazy
this would run server-side as well. The resource is fetched once when the resources cache is cold.