Custom Hooks - GRIM-Technologies/react-training.adv GitHub Wiki

Use your branch where Redux is implemented, or the supplied with-redux branch.

Task #1 – Build a utility function

The /hooks page contains listing of various information. Implement a function that ensures that we do not render resources unless the user has the appropriate permission to view that resource.

  • users'ACCESS_USERS'
  • albums'ACCESS_ALBUMS'

The function could be used something like this:

const mayViewUsers = hasPermission('ACCESS_USERS');

You can find the list of permissions (permissions) in src/utils.js.

Task #2 – Refactor to a custom hook

2.2 Lift state to global

Using Redux, move permissions into global state so that it can be accessed using Redux's useSelector hook. It's OK if the permissions list is hardcoded in Redux's initialState, unless you want to implement a clever way to fetch it from somewhere, or simulate an async request.

2.3 Refactor to custom hook

Now that we need useSelector to retrieve permissions from Redux, it makes sense to refactor the utility function for checking permissions into a hook instead. The hook could be used something like this:

const mayViewUsers = usePermission('ACCESS_USERS');

Task #3 - Further improvements

We can make this hook even more useful to us by refactoring it, so we don't need to call it several times in order to get several permission flags. Feel free to refactor the hook further to eliminate multiple calls to it. Some ideas on how to use this hook are listed below, build it how you want!

// Array // arguments
const [mayViewUsers, mayViewAlbums, mayViewComments] = usePermissions('ACCESS_USERS', 'ACCESS_ALBUMS', 'ACCESS_COMMENTS');

// Object // array
const {
  hasAccessUsersPermission,
  hasAccessAlbumsPermission,
  hasAccessCommentsPermission
} = usePermissions(['ACCESS_USERS', 'ACCESS_ALBUMS', 'ACCESS_COMMENTS']);