Documentation

Basic concepts

To understand how to use the library you should only understand 3 basic things

  • State

  • Store

  • Provider

State

State is a just a dataset. For example a simple state that contains user name could be represented as

{
    name: "Luke Skywalker"
}

Store

Store is a JavaScript class that have a state property and setState method.

minimal-store-example.js
import { SharedStore } from 'react-shared-state'

class MyStore extends SharedStore {}

State property is an empty object by default

To update the state you should use setState method.

It works the same as react's setState method

Right now setState accepts only object to update the state. Using updater as a function doesn't supported

Provider

Provider is a component that keeps your store and pass the store to your components.

To create provider call createProvider

You add it to the root component of your application.

After that you can use it in your components using YourProvider.connect

Connect is a High Ordered Component that accepts a mapStoreToProps callback with two arguments:

  • store — a store instance being automatically created

  • ownProps — props passed to the component

To update the state you can use store.setState()

To access the state use store.state

Extending store

While you can use setState to change you state it's better to hide your logic with custom methods implementation

For example instead of setting name using setState it's better to add a custom method setName.

First of all let's create a Store class and pass it to createProvider.

Now you can use it in your component in props

Since we've used class properties definition ()=> to declare the method we can pass it in mapStoreToProps.

Using State with API calls

Sometimes you have to get some data from the external source, for example API. Wonder where to add it? Just add it the store!

And use as a simple call

Also we've added a loading flag to indicate something is going one.

Working example available at https://codesandbox.io/s/wy308n0k88

Logging

You can add logging for all stores

or individually

Last updated