redux-saga-jwt
TypeScript icon, indicating that this package has built-in type declarations

1.1.1-next.3 • Public • Published

redux-saga-jwt

npm version CircleCI Coverage Status license

Features

  1. Multiple token management
  2. Support Typescript

Installation

npm i redux-saga-jwt

Setup

import {
  createActionCreators,
  createJWT,
  JWTState,
  remove,
  set,
  TokenObject
} from 'redux-saga-jwt'
 
const jwt = createJWT({
  *setTokens(state) {
    yield Storage.setToken(state);
  },
  *getTokens() {
    return (yield Storage.getToken()) as JWTState;
  },
  *refreshToken(id, token) {
    const newToken = yield LoginService.refresh(token.refreshToken!);
    yield put(set(id, newToken as TokenObject))
  },
})
 
const selectors = jwt.createSelectors('main')
const actionCreators = createActionCreators('main')
 
const rootReducer = combineReducers({
  jwt: jwt.reducer,
})
 
const sagaMiddleware = createSagaMiddleware()
 
sagaMiddleware.run(function* () {
  yield all([
    jwt.saga,
  ])
})

Example

TODO: upload to codesandbox

Usage

  1. Set token after login
const login = async () => {
    const token = await LoginService.login();
    dispatch(actionCreators.set(token))
}
  1. Remove your token when user logs out
const logout = async () => {
    await LoginService.login();
    dispatch(actionCreators.remove())
}
  1. Selectors

If token is null, isTokenExpired will return true

import {useSelector} from 'react-redux'
 
const isInitialized = useSelector(selectors.isInitialized)
const isAuthenticated = useSelector(selectors.isAuthenticated)

FAQ

What should I do if I don't need to refresh token?

  1. Set refreshInterval to -1 in your token object
import {createActionCreators, useDispatch} from "react-redux";
 
const actionCreators = createActionCreators('main')
 
const dispatch = useDispatch();
 
dispatch(actionCreators.set({
    ...(YOUR_TOKEN),
    refreshInterval: -1
}))
My refresh token never expired, what should I do?

Readme

Keywords

none

Package Sidebar

Install

npm i redux-saga-jwt

Weekly Downloads

12

Version

1.1.1-next.3

License

MIT

Unpacked Size

49.3 kB

Total Files

38

Last publish

Collaborators

  • kencckw