redux-saga-jwt
v1.1.1-next.3
Published
Token management for single page application
Downloads
29
Readme
redux-saga-jwt
Features
- Multiple token management
- 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
- Set token after login
const login = async () => {
const token = await LoginService.login();
dispatch(actionCreators.set(token))
}
- Remove your token when user logs out
const logout = async () => {
await LoginService.login();
dispatch(actionCreators.remove())
}
- 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?
- 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
}))