0.0.13 • Published 4 years ago
@onaio/session-reducer v0.0.13
session reducer
This is a simple reducer module that provides a way to store session-type information in the redux store.
The store
Currently the session store looks like this:
/** simple user object description of fields */
export interface User {
email?: string;
gravatar?: string;
name: string;
username: string;
}
/** the session store fields description */
export interface SessionState {
extraData?: { [key: string]: any } /** an object that can hold anything, which is optional */;
authenticated: boolean /** boolean to check if user is authenticated */;
user: User /** a simple user object */;
}
Action Creators
Right now, the following action creators are provided:
authenticateUser
: for logging in a new userlogOutUser
: for logging out a logged in userupdateExtraData
: for updating extraData object
Sample code to use these actions
import { authenticateUser, logOutUser, updateExtraData } from '@onaio/session-reducer';
let sessionUser; // you would need to provide a real user object
let onadataUser; // you would need to provide a real object or leave it out
/** authenticate user action creator expects the following params
* @param {boolean} authenticated - whether the user is authenticated or not
* @param {User} user - the user object
* @param {{ [key: string]: any }} extraData - an object containing any extra information
*/
authenticateUser(true, sessionUser, onadataUser); // example usage
/** logOutUser takes no params */
logOutUser(); // example usage
/** updateExtraData action creator expects the following param
* @param {{ [key: string]: any }} extraData - an object containing any extra information
*/
updateExtraData(extraData); // example usage
Selectors
Right now, the following selectors are provided:
isAuthenticated
: check if the current user is logged ingetUser
: get the logged in usergetExtraData
: get the extra data objectgetApiToken
: get the api token of logged in usergetAccessToken
: get access token of logged in usergetOauthProviderState
: get the oauth provider state
Sample code to use these selectors
import { getExtraData, getUser, isAuthenticated } from '@onaio/session-reducer';
// we assume you have a state object defined somewhere
let state;
const authenticated = isAuthenticated(state);
const user = getUser(state);
const extraData = getExtraData(state);
Usage
Using this reducer is quite simple and can be done in one of two ways:
- Use combineReducers to ensure that the session reducer is loaded into your Redux store
OR
- Register the session reducer so that it is added to your Redux store dynamically. You would do this in the case that you are using the Reducer Registry.
sample code to register the reducer
import session, { reducerName as sessionReducer } from '@onaio/session-reducer';
import reducerRegistry from '@onaio/redux-reducer-registry';
reducerRegistry.register(sessionReducer, session);