lenzr

1.0.0 • Public • Published

lenzr

GitHub package.json version Greenkeeper badge Coverage Status Top languages Known Vulnerabilities npm bundle size David Scrutinizer Code Quality JavaScript Style Guide

Global store for React using lenses.

TL;DR Full example

import React from 'react'
import lenzr, { lensProp } from 'lenzr'

// First we will set up a new store.
const { withGlobalStore, connect } = lenzr({ count: 10 })

// Create a lens for accessing the count data in the store.
const countLens = lensProp('count')

// A simple component with the count value and a set function to manipulate the store.
const Counter = ({ count, set }) =>
  <div onClick={() => set(countLens, count + 1)}>{count}</div>

// Connect the component to the global store 
// It will provide functions to access the store (set/over/view)
// And will map data from the store throught a lens to props
const ConnectedCounter = connect({ count: countLens })(Counter)

// The App with a HOC to provide the global store.
const App = withGlobalStore(() => (
  <div>
    <h1>Counter</h1>
    <ConnectedCounter />
  </div>
))

Lenzr API

The lenzr function will return an object with the following functions:

  • withGlobalStore: HOC for making the store available for other components.
  • connect: HOC for connection other components to the store.
  • useLensGlobalStore: React Hook with contains functions to operate on the store

Store operation set/view/over

Both the connect and useLensGlobalStore exposes functions which can be used to operate on the store.

const ConnectedApp = connect()(
  ({set, over, view}) => { 
    ... 
})
const AppWithHook = () => {
  const {set, over, view} = useLensGlobalStore()
  ...
}

Important note: 'useLensGlobalStore' will always cause a re-render of the component if the store has changed. If the return value is very expensive, you could wrap it with React.useMemo.

Set

With the 'set' function a specific value can be changed or added in the store, using the given lens.

const ResetButton = connnect()(({ set }) => {
  const reset = () => set(countLens, 0)
  
  return <button onClick={reset}>Reset</button>
})

Over

Also with the 'over' function can the value be changed in the store, but instead of a value, a function is given. This function accepts the old value and needs to return the new value.

const IncButton = connnect()(({ over }) => {
  const inc = () => over(countLens, x => x + 1)
  
  return <button onClick={inc}>Increment</button>
})

View

With the 'view' function a value in the store can be viewed, it needs a lens to read it from the store.

const Counter = connnect()(({ view }) => {
  const count = view(countLens)
  
  return <div>{count}</di>v
})

Package Sidebar

Install

npm i lenzr

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

35.5 kB

Total Files

5

Last publish

Collaborators

  • justbrody