lore-hook-auth

Provides an action and reducer dedicated to fetching the current user

Example Usage

Let's say you're building an application that consumes an API that returns information about the current user from the endpoint /user.

In order to retrieve the current user, we need three things in place:

  • A model representing that endpoint,
  • An action we can invoke the fetch the user
  • A reducer we can use to store the user

Unlike the build-in blueprints, this flow is special in that the action will always communicate with the same endpoint (/user) and the reducer will only store a single object, as opposed to a set of objects like the built-in find, byId and byCid reducers.

Without this hook, if you wanted to retrieve the current user, you would need to generate the following files yourself:

src
|-actions
  |-currentUser
    |-get.js
|-models
  |-currentUser.js
|-reducers
  |-currentUser.js

The currentUser model would describe the API endpoint, currentUser.get action would retrieve the user, and the currentUser reducer would store the user.

This hook prevents you from needing to create the custom action and reducer. Instead, you only need to create the model and specify what endpoint the action should fetch the current user from.

Here is an example currentUser model, that sets the endpoint to be /user (matching our API):

module.exports = {
  endpoint: 'user'
}

Once this model exists (and assuming the modelName field in the config matches the name of this model) you can fetch the current user through a lore.connect call like this:

lore.connect(function(getState, props) {
  return {
    user: getState('currentUser')
  };
})