3

Manage persist state with simple API in React Native

 2 years ago
source link: https://reactnativeexample.com/manage-persist-state-with-simple-api-in-react-native/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

react-native-persist-state

Manage persist state with simple API in React Native

✨ Manage persist state with simple API

  • Shared state across components using Hook
  • Ability to access state outside of components
  • Fully tested and written in TypeScript

API Overview

// 1. Create a store
const store = createPersisStore<string | null>({
  key: 'authToken',
  initialData: null,
})


// 2. Use the store inside components
function HomeScreen() {
  const [authToken, setAuthToken] = usePersistState(store)
  
  if (authToken == null) {
     return <Login onSucess={setAuthToken} />
  }
  
  return <Home />
}


// 3. Access the store outside of components
function request() {
  ... 
  if (response.statusCode === 401) {
    authTokenStore.remove()
  }
}

Installation

npm install react-native-persist-state

# Used as peer dependencies
npm install recoil react-native-async-storage/async-storage

Setting Up

// Add RecoilRoot and Suspense into your root component

import { RecoilRoot } from "recoil";
import { Suspense } from "react";

function App() {
  return (
    <RecoilRoot>
      <Suspense>
        <MyApp />
      </Suspense>
    </RecoilRoot>
  )
}
React JSX

GitHub

https://github.com/incleaf/react-native-persist-state


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK