Authentication context and storing the JWT
In this section, you will use your brand-new form, powered by RHF, and connect it to the Context API. The procedure for defining a React Context API was covered in detail in Chapter 4, Getting Started with FastAPI and in this chapter, you will apply that knowledge and create a similar context for keeping track of the authentication state of the application:
- Create a new folder in the
/src
directory and name itcontexts
. Inside this folder, create a new file calledAuthContext.jsx
and create the provider:import { createContext, useState, useEffect } from ‘react’; import { Navigate } from ‘react-router-dom’; export const AuthContext = createContext(); export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [jwt, setJwt] = useState(localStorage.getItem('jwt')||null); const [message, setMessage] = useState( “Please log in” );
The context...