1.1.1-next.3 • Published 4 years ago

redux-saga-jwt v1.1.1-next.3

Weekly downloads
94
License
MIT
Repository
github
Last release
4 years ago

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?
1.1.1-next.3

4 years ago

1.1.1-next.2

4 years ago

1.1.1

4 years ago

1.1.1-next.1

4 years ago

1.1.1-next.0

4 years ago

1.0.4-beta.0

5 years ago

1.0.3

5 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.0.5

7 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago