alan2207 / react-query-auth

⚛️ Authenticate your react applications easily with react-query.
MIT License
359 stars 43 forks source link
auth authentication context-api hooks react react-query

react-query-auth

NPM

Authenticate your react applications easily with React Query.

Introduction

Using React Query has allowed us to significantly reduce the size of our codebase by caching server state. However, we still need to consider where to store user data, which is a type of global application state that we need to access from many parts of the app, but is also a server state since it is obtained from a server. This library makes it easy to manage user authentication, and can be adapted to work with any API or authentication method.

Installation

$ npm install @tanstack/react-query react-query-auth

Or if you use Yarn:

$ yarn add @tanstack/react-query react-query-auth

Usage

To use this library, you will need to provide it with functions for fetching the current user, logging in, registering, and logging out. You can do this using the configureAuth function:

import { configureAuth } from 'react-query-auth';

const { useUser, useLogin, useRegister, useLogout } = configureAuth({
  userFn: () => api.get('/me'),
  loginFn: (credentials) => api.post('/login', credentials),
  registerFn: (credentials) => api.post('/register', credentials),
  logoutFn: () => api.post('/logout'),
});

With these hooks, you can then add authentication functionality to your app. For example, you could use the useUser hook to access the authenticated user in a component.

You can also use the useLogin, useRegister, and useLogout hooks to allow users to authenticate and log out.

function UserInfo() {
  const user = useUser();
  const logout = useLogout();

  if (user.isLoading) {
    return <div>Loading ...</div>;
  }

  if (user.error) {
    return <div>{JSON.stringify(user.error, null, 2)}</div>;
  }

  if (!user.data) {
    return <div>Not logged in</div>;
  }

  return (
    <div>
      <div>Logged in as {user.data.email}</div>
      <button disabled={logout.isLoading} onClick={logout.mutate({})}>
        Log out
      </button>
    </div>
  );
}

The library also provides the AuthLoader component that can be used to handle loading states when fetching the authenticated user. You can use it like this:

function MyApp() {
  return (
    <AuthLoader
      renderLoading={() => <div>Loading ...</div>}
      renderUnauthenticated={() => <AuthScreen />}
    >
      <UserInfo />
    </AuthLoader>
  );
}

NOTE: All hooks and components must be used within QueryClientProvider.

API Reference:

configureAuth:

The configureAuth function takes in a configuration object and returns a set of custom hooks for handling authentication.

The configureAuth configuration object:

A configuration object that specifies the functions and keys to be used for various authentication actions. It accepts the following properties:

The configureAuth returned object:

configureAuth returns an object with the following properties:

If you need a more custom loading implementation, you can create your own AuthLoader component and use the useUser hook to fetch the authenticated user and handle the loading and error states yourself.

Examples:

To try out the library, check out the examples folder.

Contributing

  1. Clone this repo
  2. Create a branch: git checkout -b your-feature
  3. Make some changes
  4. Test your changes
  5. Push your branch and open a Pull Request

LICENSE

MIT