redux-jam
redux-jam
is a framework for managing the complexity of multiple data
sources with different fetching and storage characteristics, while using
standard, flexible, and known systems, such as Redux.
Storing data fetched from a server locally is a very attractive method of improving user experience, but it comes with significant difficulties. Deciding when to invalidate a locally cached dataset, and how to combine remote and local data can be a source of immense complexity. This is especially true when building an application designed for offline capabilities.
Installation
npm install redux-jam
or
yarn add redux-jam
Add the JAM model reducer to your root reducer:
const rootReducer =
Defining a Schema
Before data can be manipulated a schema describing the structure of the data must be defined. There are a number of ways to do it, the two most common are to define the data manually, or import it automatically using an external package.
Manual Definition
Schemas are built using the Schema
class:
let schema =
To define models in a schema, use the merge
method, which accepts an object
argument describing a part of a schema:
merge
may be called any number of times. Each subsequent call will overwrite
any overlapping models.
The structure of the schema object is similar in some ways to the structure of a JSON-API object. Take for example the following definition of a movie:
movie: attributes: name: required: true duration: {} year: {} relationships: actors: type: "person" many: true relatedName: "actedIn" api: {} {} {} {} {} person: attributes: name: required: true api: {} {} {} {} {}
This defines two models: movie
and person
. The api
sections of each
model are placeholders for calls to API endpoints. They should return promises,
which in turn return JSON-API structured data.
Options for attributes are currently limited to required
.
Options for relationships:
-
type
-
required
-
many
-
relatedName
Django + DRF
If you're using Django and DRF, your schema can be loaded into JAM automatically, which is particularly convenient.
Refer to Django-JAM
Loading Data
Fetching data from the server is achieved with a higher order comonent,
withView
. Views collect a set of one or more queries and provide the
resultant data to a React component.
The following snippet shows a React component that loads movies whose title contains the term "Rocky", and sorts them on year:
const view = schema @Component { const moviesList = thisprops const loading queries = moviesList if !loading return <ul> queriesmovies else return null }}
Mutating data
redux-jam
provides a form like interface for mutating data.
@Component { const renderField = thisprops // TODO }