Git Product home page Git Product logo

use-state-persist's Introduction

Use State Persist

CI Coverage Status Codacy Badge npm version

A simple React Hook to persist useState in local storage.

Works on the Web and React Native.

Easily implement

  • Offline state
  • Stale while revalidate flow
  • Global state
npm install use-state-persist
# or
yarn add use-state-persist

For React Native make sure you do the following on app start up:

import { syncStorage } from 'use-state-persist';

// Initialize async storage
await syncStorage.init();

How to persists useState

Same behavior and API as useState so you can use it by easily replacing the useState hook for the calls which you want to persist offline.

import { useStatePersist as useState } from 'use-state-persist';

const Component = () => {
  // Before
  //const [counter, setCounter] = useState(0);
  const [counter, setCounter] = useState('@counter', 0);

  return <CounterDisplay value={counter} />;
};

Stale While Revalidate

import { useStatePersist as useState } from 'use-state-persist';

const Component = () => {
  // Loads stale state
  const [data, setData] = useState('@data');

  const fetchData = async () => {
    // Fetches new state
    const data = await fetch('/endpoint');
    setData(data);
  };

  useEffect(() => {
    fetchData();
  }, []);

  return <DataDisplay value={data} />;
};

Global State

Simple event system allows all the storage writes to be dispatched to all hooks . That means that all useStatePersist() can be used as a global state by sharing the same key useStatePersist('@globalKey')

To avoid that just make sure that the key being passed to the hook is unique useStatePersist('@uniqueKey')

const CounterButton = () => {
  const [counter, setCounter] = useState('@counter');

  return <Button onClick={() => setCounter(counter => counter++)} />;
};

State will be updated across multiple components

const ShowCounter = () => {
  const [counter, setCounter] = useState('@counter', 0);

  return <CounterDisplay value={counter} />;
};

Cache Invalidation

There are some cases where you might want to clear all the local storage cache for the hook, pending a certain change in state in the app.

This will clear all the local storage items use by the useStatePersist hook when the key changes.

Use Cases

  • User/App State changes
  • User Log out
  • Environment variable changes
import { invalidateCache } from 'use-state-persist';

invalidateCache('CACHE_KEY');

// You can also send a promise which will compare the result
invalidateCache(async () => 'CACHE_KEY');

React Native

Init prepares the SyncStorage to work synchronously, by getting all values for all keys stored on AsyncStorage. You can use the init method on the web without any side effects to keep code consistency.

import { syncStorage } from 'use-state-persist';

await syncStorage.init();

use-state-persist's People

Contributors

codacy-badger avatar leoafarias avatar robertsasak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

use-state-persist's Issues

Loses sync with global @id

const Toggler = (props) => {
    const [count, setCount] = useState(props.id, 0)
    return (
        <View>
            <TouchableHighlight
                onPress={() => {
                    const newCount = count === 4 ? 0 : count + 1
                    setCount(newCount)
                }}
            >
                <Text>[Increment]</Text>
            </TouchableHighlight>
            <Text>COUNT: {count}</Text>
        </View>
    )
}
const Home = (props) => {
    return (
        <View>
            <Toggler id="hello" />
            <Toggler id="hello" />
        </View>
    )
}

It seems that when the count is set to 0, only one of the Toggler renders. The other doesn't render.

Error: Sync Storage init() needs to be called.

I did the basic implementation of setting the state using useStatePersist instead of the default useState hook after installing the package.

The state is loading as usual (querying from API) but is not persisting, and on top of it, this error shows up whenever the screen is opened - "Error: Sync Storage init() needs to be called before using it."

Does not persist

Great library! Should be built-in to RN.

I'm using "react-native": "0.63.4", but seem to have problems with the simple usage.
When I reload the app, the state resets to 0.

import { useStatePersist as useState } from 'use-state-persist'

const Thing = (props) => {
    const [count, setCount] = useState('@counter', 0)
    return (
        <View>
            <Text>{count}</Text>
            <Toucher
                onPress={() => {
                    setCount(count + 1)
                }}
             
            >
                <Text>INCREMENT</Text>
            </Toucher>
        </View>
    )
}

Booleans not working

Booleans are not being properly loaded after I refresh the page. Any workarounds for this?

Thank youu!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.