3
Manage persist state with simple API in React Native
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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK