diff --git a/.babelrc b/.babelrc
new file mode 100644
index 0000000..c808f28
--- /dev/null
+++ b/.babelrc
@@ -0,0 +1,39 @@
+{
+"presets": [
+ [
+ "@babel/env",
+ {
+ "modules": false,
+ "exclude": [
+ "@babel/plugin-transform-regenerator"
+ ]
+ }
+ ],
+ "@babel/react"
+],
+"plugins": [
+ [
+ "module:fast-async",
+ {
+ "compiler": {
+ "noRuntime": true
+ }
+ }
+ ]
+],
+"env": {
+ "test": {
+ "presets": [
+ [
+ "@babel/env",
+ {
+ "modules": "commonjs",
+ "exclude": [
+ "@babel/plugin-transform-regenerator"
+ ]
+ }
+ ]
+ ]
+ }
+}
+}
diff --git a/.eslintrc b/.eslintrc
new file mode 100644
index 0000000..05544dd
--- /dev/null
+++ b/.eslintrc
@@ -0,0 +1,10 @@
+{
+ "parser": "babel-eslint",
+ "extends": ["react-app", "prettier"],
+ "env": {
+ "es6": true
+ },
+ "parserOptions": {
+ "sourceType": "module"
+ }
+}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a57a052
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
+# dependencies
+node_modules
+
+# builds
+dist
+
+# misc
+.DS_Store
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+.history
diff --git a/.size-snapshot.json b/.size-snapshot.json
new file mode 100644
index 0000000..3802b0d
--- /dev/null
+++ b/.size-snapshot.json
@@ -0,0 +1,21 @@
+{
+ "dist/index.js": {
+ "bundled": 31464,
+ "minified": 16507,
+ "gzipped": 5069
+ },
+ "dist/index.es.js": {
+ "bundled": 31098,
+ "minified": 16202,
+ "gzipped": 4995,
+ "treeshaked": {
+ "rollup": {
+ "code": 75,
+ "import_statements": 57
+ },
+ "webpack": {
+ "code": 1135
+ }
+ }
+ }
+}
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..779e3d4
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020 Ari Bouius
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e2e8016
--- /dev/null
+++ b/README.md
@@ -0,0 +1,552 @@
+# jsonapi-react
+A minimal [JSON:API](https://jsonapi.org/) client and [React](https://reactjs.org/) hooks for fetching, updating, and caching remote data.
+
+## Features
+- Declarative API queries and mutations
+- JSON:API schema serialization + normalization
+- Query caching + garbage collection
+- Automatic refetching (stale-while-revalidate)
+- SSR support
+
+## Purpose
+In short, to provide a similar client experience to using `React` + [GraphQL](https://graphql.org/).
+
+The `JSON: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 are [several projects](https://jsonapi.org/implementations/) that provide good `JSON:API` implementations,
+but none offer a seamless integration with `React` without incorporating additional libraries and/or model abstractions.
+
+Libraries like [react-query](https://github.com/tannerlinsley/react-query) and [SWR](https://github.com/zeit/swr) (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 like [json-api-normalizer](https://github.com/yury-dymov/json-api-normalizer). But both require a non-trivial amount of configuration for cache invalidation and state updates,
+both of which can be abstracted away when working with a defined schema.
+
+## Support
+- React 16.8 or later
+- Browsers [`> 1%, not dead`](https://browserl.ist/?q=%3E+1%25%2C+not+dead)
+- Consider polyfilling:
+ - [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+ - [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
+
+## Documentation
+- [Installation](#installation)
+- [Getting Started](#getting-started)
+- [Queries](#queries)
+- [Mutations](#mutations)
+- [Deleting](#deleting-resources)
+- [Caching](#caching)
+- [Manual Requests](#manual-requests)
+- [Server-Side Rendering](#server-side-rendering)
+- [API Reference](#api)
+ - [useQuery](#useQuery)
+ - [useMutation](#useMutation)
+ - [useIsFetching](#useClient)
+ - [useClient](#useClient)
+ - [ApiClient](#ApiClient)
+ - [ApiProvider](#ApiProvider)
+ - [renderWithData](#renderWithData)
+## Installation
+```
+npm i --save jsonapi-react
+```
+
+## Getting Started
+To begin you'll need to create an [ApiClient](#ApiClient) instance and wrap your app with a provider.
+```javascript
+import { ApiClient, ApiProvider } from 'jsonapi-react'
+import schema from './schema'
+
+const client = new ApiClient({
+ url: 'https://my-api.com',
+ schema,
+})
+
+const Root = (
+
+
+
+)
+
+ReactDOM.render(
+ Root,
+ document.getElementById('root')
+)
+```
+
+### Schema Definition
+In order to accurately serialize mutations and track which resource types are associated with each request, the `ApiClient` class requires a schema object that describes your API's resources and their relationships.
+
+```javascript
+new ApiClient({
+ schema: {
+ todos: {
+ type: 'todos',
+ relationships: {
+ user: {
+ type: 'users',
+ }
+ }
+ },
+ users: {
+ type: 'users',
+ relationships: {
+ todos: {
+ type: 'todos',
+ }
+ }
+ }
+ }
+})
+```
+
+As an added benefit, you can also describe and customize how fields get deserialized. Field configuration is entirely _additive_, so any omitted fields are simply passed through unchanged.
+```javascript
+const schema = {
+ todos: {
+ type: 'todos',
+ fields: {
+ title: 'string', // shorthand
+ priority: {
+ type: 'number', // converts value to integer
+ },
+ status: {
+ resolve: status => {
+ return status.toUpperCase()
+ },
+ },
+ created: {
+ type: 'date', // converts value to a Date object
+ readOnly: true // removes field for mutations
+ }
+ },
+ relationships: {
+ user: {
+ type: 'users',
+ }
+ }
+ },
+}
+```
+
+## Queries
+To make a query, call the [useQuery](#useQuery) hook with the `type` of resource you are fetching. The returned object will contain the query result, as well as information relating to the request.
+```javascript
+import { useQuery } from 'jsonapi-react'
+
+function Todos() {
+ const { data, meta, error, isLoading, isFetching } = useQuery('todos')
+
+ return (
+
+ isLoading ? (
+
...loading
+ ) : (
+ data.map(todo => (
+
{todo.title}
+ ))
+ )
+
+ )
+}
+```
+
+The argument simply gets converted to an API endpoint string, so the above is equivalent to doing
+```javascript
+useQuery('/todos')
+```
+
+As syntactic sugar, you can also pass an array of URL segments.
+```javascript
+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 the _last_ value of the array. The object gets serialized to a `JSON:API` compatible query string using [qs](https://github.com/ljharb/qs).
+```javascript
+useQuery(['todos', {
+ filter: {
+ complete: 0,
+ },
+ include: [
+ 'comments',
+ ],
+ page: {
+ number: 1,
+ size: 20,
+ },
+}])
+```
+
+If a query isn't ready to be requested yet, pass a _falsey_ value to defer execution.
+```javascript
+const id = null
+const { data: todos } = useQuery(id && ['users', id, 'todos'])
+```
+
+### Normalization
+The API response data gets automatically deserialized into a nested resource structure, meaning this...
+```javascript
+{
+ "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...
+```javascript
+{
+ id: "1",
+ title: "Clean the kitchen!",
+ user: {
+ id: "2",
+ name: "Steve"
+ }
+}
+```
+
+## Mutations
+To run a mutation, first call the [useMutation](#useMutation) hook with a query key. The return value is a tuple that includes a `mutate` function, and an object with information related to the request. Then call the `mutate` function to execute the mutation, passing it the data to be submitted.
+```javascript
+import { useMutation } from 'jsonapi-react'
+
+function AddTodo() {
+ const [title, setTitle] = useState('')
+ const [addTodo, { isLoading, data, error, errors }] = useMutation('todos')
+
+ const handleSubmit = async e => {
+ e.preventDefault()
+ const result = await addTodo({ title })
+ }
+
+ return (
+
+ )
+}
+```
+
+### Serialization
+The mutation function expects a [normalized](#normalization) resource object, and automatically handles serializing it. For example, this...
+```javascript
+{
+ id: "1",
+ title: "Clean the kitchen!",
+ user: {
+ id: "1",
+ name: "Steve",
+ }
+}
+```
+
+Gets serialized to...
+```javascript
+{
+ "data": {
+ "id": "1",
+ "type": "todos",
+ "attributes": {
+ "title": "Clean the kitchen!"
+ },
+ "relationships": {
+ "user": {
+ "data": {
+ "type": "users",
+ "id": "1"
+ }
+ }
+ }
+ }
+}
+```
+
+## Deleting Resources
+`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 a [manual request](#manual-requests) on the `client` instance.
+
+
+## Caching
+`jsonapi-react` implements a `stale-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.
+
+### Configuration
+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.
+```javascript
+const client = new ApiClient({
+ cacheTime: 5 * 60,
+ staleTime: 60,
+})
+```
+
+To override the global caching rules, pass a configuration object to `useQuery`.
+```javascript
+useQuery('todos', {
+ cacheTime: 5 * 60,
+ staleTime: 60,
+})
+```
+
+### Invalidation
+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, the `useMutation` hook accepts a `invalidate` option.
+```JavaScript
+const [mutation] = useMutation(['todos', 1], {
+ invalidate: ['todos', 'comments']
+})
+```
+
+## Manual Requests
+Manual API requests can be performed through the client instance, which can be obtained with the [useClient](#useClient) hook
+
+```javascript
+import { useClient } from 'jsonapi-react'
+
+function Todos() {
+ const client = useClient()
+}
+```
+
+The client instance is also included in the object returned from the `useQuery` and `useMutation` hooks.
+```javascript
+function Todos() {
+ const { client } = useQuery('todos')
+}
+
+function EditTodo() {
+ const [mutate, { client }] = useMutation('todos')
+}
+```
+The client request methods have a similar signature as the hooks, and return the same response structure.
+
+```javascript
+# Queries
+const { data, error } = await client.fetch(['todos', 1])
+
+# Mutations
+const { data, error, errors } = await client.mutate(['todos', 1], { title: 'New Title' })
+
+# Deletions
+const { error } = await client.delete(['todos', 1])
+```
+
+## Server-Side Rendering
+Full SSR support is included out of the box, and requires a small amount of extra configuration on the server.
+
+```javascript
+import { ApiProvider, ApiClient, renderWithData } from 'jsonapi-react'
+
+const app = new Express()
+
+app.use(async (req, res) => {
+ const client = new ApiClient({
+ ssrMode: true,
+ url: 'https://my-api.com',
+ schema,
+ })
+
+ const Root = (
+
+
+
+ )
+
+ const [content, initialState] = await renderWithData(Root, client)
+
+ const html =