React Redux Permission
npm install react-redux-permission> React Redux Permission controls rendering of permission components & routes using redux.
 
``bash`
npm install --save react-redux-permission
`tsx
import { createStore, compose } from 'redux';
import { combineReducers } from "redux";
import { permissionsReducer as permissions } from "react-redux-permission";
export const configureStore = (initialState = {}) => {
return createStore(
combineReducers({
permissions,
}), initialState,);
}
`
`tsx
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { configureStore } from "./redux/store";
import { Provider } from "react-redux";
import { PermissionProvider, Show, useAccess } from "react-redux-permission";
const store = configureStore();
const App = () => {
const { hasPermission, definePermission, isLoaded } = useAccess();
useEffect(() => {
definePermission(["feature:read", "feature:write"]);
}, []);
const canRead = hasPermission("feature:read");
if (!isLoaded) return
return (
})})ReactDOM.render(
document.getElementById("root")
);
`
By Wrapping up your application with , all your hierarchy components will have ability to work with react-redux-permission.
`tsx
import { PermissionProvider } from "react-redux-permission";
`
Has 2 available props
| params | value | default value | description |
|:------------:|:--------:|:------------------------------------:|:----------------:|
| store | object | REQUIRED | Redux store object. |
| reducerKey | string | permissionsReducer | State key of your reducer. |
A Component can be use when want to render something conditionally, you can pass permission(s) into when prop.
`tsx
import { Show } from "react-redux-permission";
fallback={
Has 2 available props
| params | value | default value | description |
|:------------:|:--------:|:------------------------------------:|:----------------:|
| when | string / array | REQUIRED | The permission(s) we want to check against. |
| fallback | ReactNode | - | What to render when the user doesn't have access. |
$3
A hook gives you access to
PermissionContext context.#### isLoaded
isLoaded will be false if
definePermission has never been called. Once definePermission is called we assume isLoaded is true. This flag can be used to prevent loading the app until permissions have been fetched and loaded.`tsx
definePermission(["feature:read", "feature:write"]);
`you can use action too, to define permissions through redux as below.
`tsx
import { definePermission as define } from "react-redux-permission";import { useDispatch } from 'react-redux';
export const ExampleComponent = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(define(["feature:read", "feature:write"]))
},[])
return
example component
}
`#### hasPermission
`tsx
const canRead = hasPermission("feature:read");
const canWrite = hasPermission("feature:write");
const canDelete = hasPermission("feature:delete");
``MIT © patelmayankce