To use the Context API in your React app, you need to create a context, provide it to the components that need it, and consume it within those components. Below is the updated version of your code that includes the use of the Context API for managing a global state.
Step 1: Create a Context
Create a new file called MyContext.js
to define your context.
javascript:import React, { createContext, useState } from 'react'; // Create the context export const MyContext = createContext(); // Create a provider component export const MyProvider = ({ children }) => { const [state, setState] = useState({ user: null }); return (
{children} ); };
Step 2: Wrap Your Application with the Provider
Modify your App.js
to wrap your routes with the MyProvider
component.
} >javascript:import React from 'react'; import { BrowserRouter, Routes, Route } from "react-router-dom"; import AdminLogin from "./Component/AdminLoginPage/AdminLogin"; import Dashboard from "./Dashbord/dashbord"; import PrivateRoute from "./Component/PivateRoute/PrivateRoute"; import MainDashbord from "./Dashbord/MainDashbord/MainDashbord"; import { MyProvider } from './MyContext'; function App() { return (
} /> } />
Step 3: Consume the Context in Your Components
In any component where you need to access the context, use the useContext
hook.
For example, in AdminLogin.js
:
javascrt:
Step 4: Update the PrivateRoute
to Use Context
Update PrivateRoute
to check the context state instead of localStorage:
javascript
import { useState, useContext } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { MyContext } from '../../MyContext';
const AdminLogin = () => {
const navigate = useNavigate();
axios.defaults.withCredentials = true;
const { setState } = useContext(MyContext); // Use context here
const [error, setError] = useState(null);
const [values, setValues] = useState({
email: "",
password: "",
});
const handleSubmit = (event) => {
event.preventDefault();
axios
.post("http://localhost:8080/api/adminlogin", values)
.then((result) => {
if (result.data.loginStatus) {
localStorage.setItem("valid", true);
setState({ user: values.email }); // Update context state
navigate("/dashboard");
} else {
setError(result.data.Error);
}
})
.catch((err) => console.log(err));
};
return (
Login Admin
{error && error}
);
};
export default AdminLogin;
import { useContext } from 'react';
import PropTypes from 'prop-types';
import { Navigate } from 'react-router-dom';
import { MyContext } from '../../MyContext';
const PrivateRoute = ({ children }) => {
const { state } = useContext(MyContext);
return state.user ? children : <Navigate to="/adminlogin" />;
};
PrivateRoute.propTypes = {
children: PropTypes.node.isRequired,
};
export default PrivateRoute;
With these steps, you've integrated the Context API into your React app and used it in your App.js
and other relevant components.
Post a Comment