DEV Community

Cover image for LocalStorage For State Management
ahgsql
ahgsql

Posted on • Updated on

LocalStorage For State Management

Check out my project on Github

Sample Todo App made with this package: TodoList with LSFR

localState for React

Get Advance of LocalStorage which using by all modern browsers.

The localStorage and sessionStorage properties allow to save key/value pairs in a web browser.
The localStorage object stores data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

localStorage for State Management

NPM JavaScript Style Guide

Install

npm install  local-state-for-react
Enter fullscreen mode Exit fullscreen mode

or

yarn add  local-state-for-react
Enter fullscreen mode Exit fullscreen mode

Methods

Determining Default State

freshState(initial)

Initializes state with default values.
This function needs to be called outside of component function.

freshState({ input1: 1 })
Enter fullscreen mode Exit fullscreen mode

 

Writing To State

writeState(path,value)

Writes state value on given path
 

Getting Data From State

readState(path)

Returns state value

readState('stateName').someCustomProperty
Enter fullscreen mode Exit fullscreen mode

Listening For Changes

System uses event dispatchers and React reducers for manually forcing re-rendering component which uses that state value.

So every component needs to useSubscribe method.
This method also returns single or multiple objects with, their values.

useSubscribe(...fields)

Listens for changes and Returns state values

const input1 = useSubscribe('input1')
Enter fullscreen mode Exit fullscreen mode

or

const { name, email } = useSubscribe('name', 'email')
Enter fullscreen mode Exit fullscreen mode

Usage

import { writeState, freshState, useSubscribe } from 'local-state-for-react'
freshState({ input1: 1 })
const App = () => {
  const input1 = useSubscribe('input1')
  return (
    <div>
      <h2>Hi From Local-State Package!</h2>
      <h1>{input1}</h1>
      <button
        onClick={() => {
          writeState('input1', input1 + 1)
        }}
      >
        Click To Change State!
      </button>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

License

MIT © ahgsql

Top comments (3)

Collapse
 
hadihammurabi profile image
Hadi Hidayat Hammurabi

Please put Github URL for this project.

Collapse
 
ahgsql profile image
ahgsql

Added, project and example app, also updated documentation

Collapse
 
hadihammurabi profile image
Hadi Hidayat Hammurabi

Really fun to know that. Thank you.