- Notifications
You must be signed in to change notification settings - Fork27
A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
License
aribouius/jsonapi-react
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A minimalJSON:API client andReact hooks for fetching, updating, and caching remote data.
- Declarative API queries and mutations
- JSON:API schema serialization + normalization
- Query caching + garbage collection
- Automatic refetching (stale-while-revalidate)
- SSR support
In short, to provide a similar client experience to usingReact
+GraphQL.
TheJSON:API
specification offers numerous benefits for writing and consuming REST API's, but at the expense of clients being required to manage complex schema serializations. There areseveral projects that provide goodJSON:API
implementations,but none offer a seamless integration withReact
without incorporating additional libraries and/or model abstractions.
Libraries likereact-query andSWR (both of which are fantastic, and obvious inspirations for this project) go a far way in bridging the gap when coupled with a serialization library likejson-api-normalizer. But both require a non-trivial amount of cache invalidation configuration, given resources can be returned from any number of endpoints.
- React 16.8 or later
- Browsers
> 1%, not dead
- Consider polyfilling:
- Installation
- Getting Started
- Queries
- Mutations
- Deleting
- Caching
- Manual Requests
- Server-Side Rendering
- API Reference
npm i --save jsonapi-react
To begin you'll need to create anApiClient instance and wrap your app with a provider.
import{ApiClient,ApiProvider}from'jsonapi-react'importschemafrom'./schema'constclient=newApiClient({url:'https://my-api.com', schema,})constRoot=(<ApiProviderclient={client}><App/></ApiProvider>)ReactDOM.render(Root,document.getElementById('root'))
In order to accurately serialize mutations and track which resource types are associated with each request, theApiClient
class requires a schema object that describes your API's resources and their relationships.
newApiClient({schema:{todos:{type:'todos',relationships:{user:{type:'users',}}},users:{type:'users',relationships:{todos:{type:'todos',}}}}})
You can also describe and customize how fields get deserialized. Field configuration is entirelyadditive, so any omitted fields are simply passed through unchanged.
constschema={todos:{type:'todos',fields:{title:'string',// shorthandstatus:{resolve:status=>{returnstatus.toUpperCase()},},created:{type:'date',// converts value to a Date objectreadOnly:true// removes field for mutations}},relationships:{user:{type:'users',}}},}
To make a query, call theuseQuery hook with thetype
of resource you are fetching. The returned object will contain the query result, as well as information relating to the request.
import{useQuery}from'jsonapi-react'functionTodos(){const{ data, meta, error, isLoading, isFetching}=useQuery('todos')return(<div> isLoading ? (<div>...loading</div> ) : ( data.map(todo =>(<divkey={todo.id}>{todo.title}</div> )) )</div>)}
The argument simply gets converted to an API endpoint string, so the above is equivalent to doing
useQuery('/todos')
As syntactic sugar, you can also pass an array of URL segments.
useQuery(['todos',1])useQuery(['todos',1,'comments'])
To apply refinements such as filtering, pagination, or included resources, pass an object of URL query parameters as thelast value of the array. The object gets serialized to aJSON:API
compatible query string usingqs.
useQuery(['todos',{filter:{complete:0,},include:['comments',],page:{number:1,size:20,},}])
If a query isn't ready to be requested yet, pass afalsey value to defer execution.
constid=nullconst{data:todos}=useQuery(id&&['users',id,'todos'])
The API response data gets automatically deserialized into a nested resource structure, meaning this...
{"data":{"id":"1","type":"todos","attributes":{"title":"Clean the kitchen!"},"relationships":{"user":{"data":{"type":"users","id":"2"}},},},"included":[{"id":2,"type":"users","attributes":{"name":"Steve"}}],}
Gets normalized to...
{id:"1",title:"Clean the kitchen!",user:{id:"2",name:"Steve"}}
To run a mutation, first call theuseMutation hook with a query key. The return value is a tuple that includes amutate
function, and an object with information related to the request. Then call themutate
function to execute the mutation, passing it the data to be submitted.
import{useMutation}from'jsonapi-react'functionAddTodo(){const[title,setTitle]=useState('')const[addTodo,{ isLoading, data, error, errors}]=useMutation('todos')consthandleSubmit=asynce=>{e.preventDefault()constresult=awaitaddTodo({ title})}return(<formonSubmit={handleSubmit}><inputtype="text"value={title}onChange={e=>setTitle(e.target.value)}/><buttontype="submit">Create Todo</button></form>)}
The mutation function expects anormalized resource object, and automatically handles serializing it. For example, this...
{id:"1",title:"Clean the kitchen!",user:{id:"1",name:"Steve",}}
Gets serialized to...
{"data":{"id":"1","type":"todos","attributes":{"title":"Clean the kitchen!"},"relationships":{"user":{"data":{"type":"users","id":"1"}}}}}
jsonapi-react
doesn't currently provide a hook for deleting resources, because there's typically not much local state management associated with the action. Instead, deleting resources is supported through amanual request on theclient
instance.
jsonapi-react
implements astale-while-revalidate
in-memory caching strategy that ensures queries are deduped across the application and only executed when needed. Caching is disabled by default, but can be configured both globally, and/or per query instance.
Caching behavior is determined by two configuration values:
cacheTime
- The number of seconds the response should be cached from the time it is received.staleTime
- The number of seconds until the response becomes stale. If a cached query that has become stale is requested, the cached response is returned, and the query is refetched in the background. The refetched response is delivered to any active query instances, and re-cached for future requests.
To assign default caching rules for the whole application, configure the client instance.
constclient=newApiClient({cacheTime:5*60,staleTime:60,})
To override the global caching rules, pass a configuration object touseQuery
.
useQuery('todos',{cacheTime:5*60,staleTime:60,})
When performing mutations, there's a good chance one or more cached queries should get invalidated, and potentially refetched immediately.
Since the JSON:API schema allows us to determine which resources (including relationships) were updated, the following steps are automatically taken after successful mutations:
- Any cached results that contain resources with a
type
that matches either the mutated resource, or its included relationships, are invalidated and refetched for active query instances. - If a query for the mutated resource is cached, and the query URL matches the mutation URL (i.e. the responses can be assumed analogous), the cache is updated with the mutation result and delivered to active instances. If the URL's don't match (e.g. one used refinements), then the cache is invalidated and the query refetched for active instances.
To override which resource types get invalidated as part of a mutation, theuseMutation
hook accepts ainvalidate
option.
const[mutation]=useMutation(['todos',1],{invalidate:['todos','comments']})
To prevent any invalidation from taking place, pass false to theinvalidate
option.
const[mutation]=useMutation(['todos',1],{invalidate:false})
Manual API requests can be performed through the client instance, which can be obtained with theuseClient hook
import{useClient}from'jsonapi-react'functionTodos(){constclient=useClient()}
The client instance is also included in the object returned from theuseQuery
anduseMutation
hooks.
functionTodos(){const{ client}=useQuery('todos')}functionEditTodo(){const[mutate,{ client}]=useMutation('todos')}
The client request methods have a similar signature as the hooks, and return the same response structure.
#Queriesconst{ data, error}=awaitclient.fetch(['todos',1])#Mutationsconst{ data, error, errors}=awaitclient.mutate(['todos',1],{title:'New Title'})#Deletionsconst{ error}=awaitclient.delete(['todos',1])
Full SSR support is included out of the box, and requires a small amount of extra configuration on the server.
import{ApiProvider,ApiClient,renderWithData}from'jsonapi-react'constapp=newExpress()app.use(async(req,res)=>{constclient=newApiClient({ssrMode:true,url:'https://my-api.com', schema,})constRoot=(<ApiProviderclient={client}><App/></ApiProvider>)const[content,initialState]=awaitrenderWithData(Root,client)consthtml=<Htmlcontent={content}state={initialState}/>res.status(200)res.send(`<!doctype html>\n${ReactDOM.renderToStaticMarkup(html)}`)res.end()})
The above example assumes that theHtml
component exposes theinitialState
for client rehydration.
<script>window.__APP_STATE__=JSON.stringify(state)</script>
On the client side you'll then need to hydrate the client instance.
constclient=newApiClient({url:'https://my-api.com',,})client.hydrate(window.__APP_STATE__)
To prevent specific queries from being fetched during SSR, theuseQuery
hook accepts assr
option.
constresult=useQuery('todos',{ssr:false})
queryArg: String | [String, Int, Params: Object] | falsey
- A string, or array of strings/integers.
- Array may contain a query parameter object as the last value.
- Iffalsey, the query will not be executed.
config: Object
cacheTime: Int | null
:- The number of seconds to cache the query.
- Defaults to client configuration value.
staleTime: Int | null
- The number of seconds until the query becomes stale.
- Defaults to client configuration value.
ssr: Boolean
- Set to
false
to disable server-side rendering of query. - Defaults to context value.
- Set to
client: ApiClient
- An optional separate client instance.
- Defaults to context provided instance.
data: Object | Array | undefined
- The normalized (deserialized) result from a successful request.
meta: Object | undefined
- A
meta
object returned from a successful request, if present.
- A
links: Object | undefined
- A
links
object returned from a successful request, if present.
- A
error: Object | undefined
- A request error, if thrown or returned from the server.
refetch: Function
- A function to manually refetch the query.
setData: Function(Object | Array)
- A function to manually update the local state of the
data
value.
- A function to manually update the local state of the
client: ApiClient
- The client instance being used by the hook.
queryArg: String | [String, Int, Params: Object]
- A string, or array of strings/integers.
- Array may contain a query parameter object as the last value.
config: Object
invalidate: String | Array
- One or more resource types to whose cache entries should be invalidated.
method: String
- The request method to use. Defaults to
POST
when creating a resource, andPATCH
when updating.
- The request method to use. Defaults to
client: ApiClient
- An optional separate client instance.
- Defaults to context provided instance.
mutate: Function(Object | Array)
- The mutation function you call with resource data to execute the mutation.
- Returns a promise that resolves to the result of the mutation.
data: Object | Array | undefined
- The normalized (deserialized) result from a successful request.
meta: Object | undefined
- A
meta
object returned from a successful request, if present.
- A
links: Object | undefined
- A
links
object returned from a successful request, if present.
- A
error: Object | undefined
- A request error, if thrown or returned from the server.
errors: Array | undefined
- Validation errors returned from the server.
isLoading: Boolean
- Indicates whether the mutation is currently being submitted.
client: ApiClient
- The client instance being used by the hook.
isFetching: Boolean
- Returns
true
if any query in the application is fetching.
- Returns
client: ApiClient
- The client instance on the current context.
url: String
- The full URL of the remote API.
mediaType: String
- The media type to use in request headers.
- Defaults to
application/vnd.api+json
.
cacheTime: Int | Null
:- The number of seconds to cache the query.
- Defaults to
0
.
staleTime: Int | null
- The number of seconds until the query becomes stale.
- Defaults to
null
.
headers: Object
- Default headers to include on every request.
ssrMode: Boolean
- Set to
true
when running in a server environment. - Defaults to result of
typeof window === 'undefined'
.
- Set to
formatError: Function(error)
- A function that formats a response error object.
formatErrors: Function(errors)
- A function that formats a validation error objects.
fetch: Function(url, options)
- Fetch implementation - defaults to the global
fetch
.
- Fetch implementation - defaults to the global
fetchOptions: Object
- Default options to use when calling
fetch
. - SeeMDN for available options.
- Default options to use when calling
fetch(queryKey: String | [String, Int, Params: Object], [config]: Object)
- Submits a query request.
mutate(queryKey: String | [String, Int, Params: Object], data: Object | Array, [config]: Object)
- Submits a mutation request.
delete(queryKey: String | [String, Int, Params: Object], [config]: Object)
- Submits a delete request.
clearCache()
- Clears all cached requests.
addHeader(key: String, value: String)
- Adds a default header to all requests.
removeHeader(key: String)
- Removes a default header.
isFetching()
- Returns
true
if a query is being fetched by the client.
- Returns
subscribe(callback: Function)
- Subscribes an event listener to client requests.
- Returns a unsubscribe function.
hydrate(state: Array)
- Hydrates a client instance with state after SSR.
client: ApiClient
- The API client instance that should be used by the application.
element: Object
- The root React element of the application.
client: ApiClient
- The client instance used during rendering.
content: String
- The rendered application string.
initialState: Array
- The extracted client state.
About
A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors8
Uh oh!
There was an error while loading.Please reload this page.