react-ion-store

Logo

State and network handling in React

View the Project on GitHub jeroenptrs/react-ion-store

Setup

Installation

If you’re using NPM, use

npm i --save react-ion-store

If you prefer yarn, use

yarn add react-ion-store

The Store

The react-ion store is comprised of two kinds of values:

These translate in two properties you’re using to configure the provider of your store:

Setting up the StoreProvider

The StoreProvider is a parent component that wraps your entire app (or from whatever scope is needed), providing it with the store and staticKeys properties discussed in the topic above.

You only need to define your StoreProvider once in your app, preferably at the top-most level.

Many ProviderComponents are set within the index.js file, most notably theme providers for Material UI and JSS. Since we can consider our ValueMap as a theme for our store, we apply the logic the same way.

In this example, we’re setting up the store and staticKeys in separate variables, before passing them to the store.

// index.js
import React from "react";
import ReactDOM from "react-dom";
import StoreProvider from "react-ion-store";

import App from "./App";

const store = {
  title: "My static title!",
  subtitle: "A subtitle, also static!",
  counter: 0
};

const staticKeys = ["title", "subtitle"];

ReactDOM.render(
  <StoreProvider store={store} staticKeys={staticKeys}>
    <App />
  </StoreProvider>,
  document.getElementById("root")
);

Static keys are optional

If you don’t want to lock in keys as static, you don’t need to pass a staticKeys prop. This is just as valid:

const store = { counter: 0 };

ReactDOM.render(
  <StoreProvider store={store}>
    <App />
  </StoreProvider>,
  document.getElementById("root")
);

Prevent reserved keywords

The terms get, set and call are reserved within the react-ion store, if you pass their keys in either of the ValueMap’s parameters, they will be filtered out.

As an example, this will not work:

const store = {
  get: () => "My static title!"
};

const staticKeys = ["get"];

Using the store

We advise you to use the withStore Higher-Order Component, but you can also use the Consumer component to access your store.

The Consumer works in the same way as the StoreProvider: you wrap it around your presentational logic:

// MyTitle.js
import React from "react";
import { Consumer } from "react-ion-store";

export default class MyTitle extends React.Component {
  render() {
    return <Consumer>{store => <h1>{store.get("title")}</h1>}</Consumer>;
  }
}

Drawbacks of Consumer

The way described above is not ideal. Ideally, we want to be able to:

withStore will pass the store to your props, allowing you to use it everywhere in your component! This is why you should definitely check out the next section on getting values, or you can go straight to the Higher-Order Component API documentation.