import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import Loader from "../views/Loader/Loader";
import { FaInstagram } from "react-icons/fa";
const WithAuth = (WrappedComponent) => {
return function ProtectedComponent(props) {
// Accept props here
const [isAuthorized, setIsAuthorized] = useState(null);
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem("token");
console.log("Token being sent:", token);
if (!token || token.trim() === "") {
setIsAuthorized(false);
return;
}
axios
.get("http://localhost:3000/users/authenticate", {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => {
console.log("Authentication Response:", response.data);
setIsAuthorized(response.data.message === "Authenticated");
})
.catch((error) => {
console.error("Authentication Error:", error.response?.data || error);
setIsAuthorized(false);
});
}, []);
if (isAuthorized === null) {
return ;
}
if (!isAuthorized) {
return (
Unauthorized! Please log in.
{navigate('/login')}}
className="flex items-center justify-center gap-2 px-6 py-3 text-white font-semibold rounded-full bg-gradient-to-r from-pink-500 via-red-500 to-yellow-500 shadow-md hover:opacity-90 transition duration-300">
Sign in with Instagram
);
}
// Pass down all props to WrappedComponent
return ;
};
};
export default WithAuth;
< /code>
Утверждает: < /p>
import React from "react";
import { Routes, Route } from "react-router-dom";
import Register from "../views/register/Register";
import Login from "../views/login/Login";
import Profile from "../views/profile/Profile";
import WithAuth from "../components/withAuth";
const ProfileWithAuth = WithAuth(Profile); // Define it outside the component
const AppRoutes = () => {
return (
{" "}
{/* This now correctly passes props */}
);
};
export default AppRoutes;
< /code>
Мой вопрос: < /p>
Зачем проходить реквизиты в ProtectectComponenet? Используйте Corelation с ванилью JS немного Exmaple ..
2. return ; Почему мы возвращаем {... реквизит} в этой обернутой функции тоже?
3.3. Понять для GPT -gpt.>
Подробнее здесь: https://stackoverflow.com/questions/794 ... -they-work
Компоненты более высокого порядка и как они работают? ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как набрать функции более высокого порядка Hinte в Python 3.6? [дублировать]
Anonymous » » в форуме Python - 0 Ответы
- 2 Просмотры
-
Последнее сообщение Anonymous
-