react-memory

Simple centralized store for react

Usage no npm install needed!

<script type="module">
  import reactMemory from 'https://cdn.skypack.dev/react-memory';
</script>

README

React Memory

A human memory based centralized storage for react.

code style: prettier HitCount

Installation

React Memory is available as an npm package.

npm install react-memory --save

The UMD build is also available on unpkg:

<!-- just memory(): -->
<script src="//unpkg.com/react-memory/dist/react-memory.umd.js"></script>

You can find the library on window.memory.

Demo

Usage

import { createMemory, Provider, connect } from 'react-memory'

// Set Default Values
const memory = createMemory({
  sensory: {
    _app: { // strictly referencing the underscore followed by lowercase component name
      _count: 0
    }
  },
  short: {
    count: 0
  },
  long: {
    $count: 0
  }
});

// If actions is a function, it gets passed the memory:
let actions = memory => ({
  // Actions can just return a state update:
  incrementSensory(state) {
    return {
      _sensory_unique_key: { _count: state._sensory_unique_key._count + 1 }
    }
  },

  incrementShort({count}) {
    return { count: count + 1 }
  },

  // Async actions can be pure async/promise functions:
  async incrementLong(state) {
    return new Promise((resolve) => {
      resolve($count: state.$count + 1);
    });
  }
})
// `_sensory${unique_value}` to map respective component
const App = connect(['_sensory_unique_key', 'count', '$count'], actions)(
  ({ _count, count, $count, incrementSensory, incrementShort, incrementLong }) => (
    <div>
      <p>Sensory: {_sensory_unique_key._count}</p>
      <p>Short: {count}</p>
      <p>Long: {$count}</p>
      <button onClick={incrementSensory}>Increment Sensory</button>
      <button onClick={incrementShort}>Increment Short</button>
      <button onClick={incrementLong}>Increment Long</button>
    </div>
  )
)

export default () => (
  <Provider memory={memory}>
    <App />
  </Provider>
)

How it works?

Mimicking the human memory model onto to the centralized store to process and retrieve the data. The data stored in central memory is categoried and initialized with all the required props for each category. Then the data is stored and retrieved based on the flow diagram.

React Memory Flow

Sensory Memory

Sensory memory is the shortest-term element of memory. It has the ability to retain data only for the duration of component lifecycle. On component unmount the value resets to its initial state. The sensory value is tightly coupled with component by referencing dynamic key _sensory followed by unique name;

Short Term (Working) Memory

It is readily-available state for the duration of application lifecycle.

Long Term Memory

Long-term memory is, obviously enough, intended for storage of information over a long period of time. The values are decoded and stored in localStorage for later retrieval.

API

createMemory

Creates a new memory with default initialized values for each memory category.

Parameters

  • $0 Object
    • $0.sensory
    • $0.short
    • $0.long
  • config (optional, default {})
  • state Object Mandatory initial state (optional, default {sensory:{},short:{},long:{}})

Examples

let memory = createMemory({
     sensory: { _viewname: {_count: 0} },
     short: { count: 0 },
     long: { $count: 0 }
  });
  memory.subscribe( state => console.log(state) );
  memory.setState({ _sensory_unique_key: {_count: 5}, $count: 6 });
  memory.getState(); Proxy Lookup Object { _sensory_unique_key: {_count: 0}, count: 0, $count: 6}
  memory.snapshot('sensory'); { _count: 5 }
  memory.resetSensory('_sensory_unique_key');
  memory.snapshot('sensory'); { _sensory_unique_key: {_count: 0}
  memory.resetLong();
  memory.snapshot('long'); { $count: 0 }

Returns memory

unsubscribe

Remove the subscribed listener function

Parameters

  • listener Function function to be detached from subscribed listeners

subscribe

Register a listener function so it can be called when state is changed

Parameters

  • listener Function function to be attached to list of subscribed listeners

resetSensory

Reset the sensory memory pass the component name eg. Card would be _card

resetLong

Reset the long term memory

setState

Update the partial state from the current proxy/state, and call the registered listeners

Parameters

  • update Object Partial values to be updated to the memory

getState

Get the current state of the memory

Returns Object state - current state of the memory

snapshot

To retrieve specific type from the memory

Parameters

  • type String memory type i.e sensory, short, long

connect

Wire a component up to the memory. Passes state as props, re-renders on change.

Parameters

  • mapStateToProps Array Memory state to be mapped the respective props using array with comma seperated values.
  • actions (Function | Object)? Action functions (pure state mappings), or a factory returning them. Every action function gets current state as the first parameter.

Examples

const Foo = connect([foo, bar])(({ foo, bar }) => <div />);
const actions = { someAction };
const Foo = connect([foo, bar], actions)(({ foo, bar, someAction }) => <div />);

Returns Component ConnectedComponent

Reporting Issues

Found a problem? Want a new feature? First of all, see if your issue or idea has already been reported. If not, just open a new clear and descriptive issue.

License

MIT License © Ajain Vivek