Я решил использовать глобальный контекст для хранения объекта профиля. Тем не менее, он повторно использует и, следовательно, переворачивает данные всякий раз, когда вы перемещаетесь на новую страницу на сайте. Таким образом, он побеждает цель глобального контекста, поскольку в любом случае он повторно выбирает каждый раз. < /P>
Вот мой файл контекста: < /p>
Код: Выделить всё
import { createContext, ReactNode, useState, useContext, useEffect } from "react";
import { Profile } from "../../types/profile";
import getProfile from "../services/getProfile";
import getUserSession from "../services/getUserSession";
interface MyProfileContextType {
profile: Profile | null;
fetchMyProfile: (id: string) => Promise;
loading: boolean;
}
const MyProfileContext = createContext(undefined);
export const MyProfileProvider = ({ children }: { children: ReactNode }) => {
const [profile, setProfile] = useState
(null);
const [loading, setLoading] = useState(false);
const fetchMyProfile = async (id: string): Promise => {
if (profile) {
return;
}
setLoading(true);
try {
const response = await getProfile(id);
if (response.error) {
throw new Error("Could not fetch MyProfile");
}
setProfile(response.profile);
} catch (error: any) {
console.error(error.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
const fetchSessionAndProfile = async () => {
const sessionResponse = await getUserSession();
if(sessionResponse && sessionResponse.session && sessionResponse.session.user && sessionResponse.session.user.id){
const id = sessionResponse.session.user.id;
fetchMyProfile(id);
}
}
if(!profile){
fetchSessionAndProfile();
} else {
setLoading(false);
}
}, [profile]);
return (
{children}
);
};
export const useMyProfile = () => {
const context = useContext(MyProfileContext);
if (!context) {
throw new Error("useMyProfile must be used within a MyProfileProvider");
}
return context;
};
< /code>
Я обертываю это вокруг своего маршрутизатора: < /p>
function App() {
return (
{
({ hideNav, showNav }) => (
)
}
);
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... h-when-use
Мобильная версия