React Session Persist 🔑 💾
Keep your session sync with your storage and React components.
Installation
yarn: yarn add react-session-persist
npm: npm install react-session-persist --save
Usage
- Wrap your app with the Session component
;; ;
- Use the hook to get and handle the session inside React components
;; const MyComponent = { const authenticated saveSession = ; const login = { ; } if authenticated return <p>User logged in!</p> return <button onClick=login>LOG IN</button>}
- Use the API to handle the session anywhere
; const loginUser = { const session = await ; await ;}
Session
This component wraps the app to keep the internal session state in sync with the storage.
Props
Prop | Default | Description |
---|---|---|
storage | cache storage | Custom storage, it allows a simple storage or an async storage |
initialData | undefined |
Optional session data. Useful if your storage is async and you want an immediate start of your app or for SSR |
useSession hook
The hook consumes the session data and methods that the Session component provides through the context.
session // object with session data authenticated // boolean flag to check if the user is authenticated user // optional object with user data saveSession // promise to save the session removeSession // promise to remove the session saveUser // promise to save optional user data loadDataFromStorage // get data directly from the storage =
API
getSession() : object
Returns the current session if exists. Otherwise, it returns undefined
.
Example:
; const session = await ;
saveSession(session: object): Promise
Saves the session in the storage and React state. Also, it updates the authenticated flag to true
.
removeSession(): Promise
Removes the session from the stores and React state. Also, it updates the authenticated flag to false
.
getUser() : object
Returns the optional user data if exists. Otherwise, it returns undefined
.
saveUser(user: object): Promise
Saves optional user data (user's name, email, etc) in the storage and React state. Also, it updates the authenticated flag to true
.
getAuthenticated(): boolean
Returns a boolean flag that is true
if there is a session in the storage.
loadDataFromStorage(): Promise<object>
Gets the data directly from the storage.
Custom Storage
You can create your own storage just providing an object with 3 methods:
const storage = : Promise? or object : Promise? or void : Promise? or void}
Each method could return a promise or value. If a method returns a promise the storage is consider an async storage.
By default react-redux-persist
uses the cache storage.
Async Storage
Check out the async example to use another storage, this example uses localForage.