MemoryStorage

MemoryStorage gives you an easy to use binding for working with data stored in memory. Often this is used as a fallback storage mechanism when others are unavailable.

Each instanciation of MemoryStorage() contains its own unique data store. You can use the one MemoryStorage instance in many ReactCoolStorageHocs and they will all remain in sync with each other.

There are no limitations on the kind of data it can store.

Because MemoryStorage doesn’t require any props, you can also access and change a MemoryStorage instance’s value outside of React. All ReactCoolStorageHocs that use the MemoryStorage will update and stay in sync, so this makes MemoryStorage particularly suitable for variables that are used inside and outside of React.

It is controlled, meaning that it will update immediately whenever the data source changes.

import MemoryStorage from 'react-cool-storage/MemoryStorage';

Config

MemoryStorage({
    // optional
    initialValue?: Object|() => Object
})
  • initialValue ?: Object|() => Object
    If provided a object, or a function that returns an object, initialValue will set the value when the storage mechanism is instanciated.

Resources

MemoryStorage requires no resources.

Props

MemoryStorage requires no props.

Outside React

MemoryStorage doesn’t require any props, so you can also access and change a MemoryStorage instance’s value outside of React. All ReactCoolStorageHocs that use the MemoryStorage will update and stay in sync.

A MyMemoryStorage instance has been added to the window. Try running MyMemoryStorage.onChange({foo: "foo"}); in the console and watch the example update at the top of this page.

Example using hooks

import React from 'react';
import ReactCoolStorageHook from 'react-cool-storage';
import MemoryStorage from 'react-cool-storage/MemoryStorage';

const MyMemoryStorage = MemoryStorage();
const useStorage = ReactCoolStorageHook(MyMemoryStorage);

export default (props) => {
    let memoryStorage = useStorage(props);

    return <div>
        <label>Data stored under a key of "foo"</label>
        <input
            value={memoryStorage.value.foo || ""}
            onChange={(event) => memoryStorage.onChange({
                foo: event.currentTarget.value
            })}
        />
        <label>Data stored under a key of "bar"</label>
        <input
            value={memoryStorage.value.bar || ""}
            onChange={(event) => memoryStorage.onChange({
                bar: event.currentTarget.value
            })}
        />
    </div>;
};

// also add this MemoryStorage instance to the window
// to demonstrate usage outside of React

window.MyMemoryStorage = MyMemoryStorage;