Где установлено контекстное состояние в контексте реагирования?Javascript

Форум по Javascript
Ответить
Anonymous
 Где установлено контекстное состояние в контексте реагирования?

Сообщение Anonymous »

Я создал приложение, которое хранит информацию пользователя в Firebase. На этой странице я пытаюсь получить данные профиля из крючка и установить данные профиля в фактическом контексте. Я понимаю, что это может быть не сейчас, но это то, что было предписано Chatgpt.export const ProfileForm = () => {
const [profile, setProfile] = useState({
username: "",
bio: "",
gender: "",
sexo: "",
edu: "",
drinking: "",
smoking: "",
dob: "",
});
const [showLogin, setShowLogin] = useState(false);
const { userProfile, setUserProfile } = useGetUserProfile();
const { userProfileContext, setUserProfileContext } = useUserProfile()

useEffect(() => {
if (userProfile) {
setProfile(userProfileContext);
}
}, [userProfile, setUserProfile]);

const { showAlert } = useContext(AlertContext);

return (



{
await signOut(auth);
window.location.href = "/login";
}}
sx={{
borderRadius: "50%",
width: 80,
height: 80,
}}>

Logout




[img]{profilePlaceholder}
style={{ maxWidth: "100%", height: "auto" }}
/>


{profile?.username || ""}

setShowLogin(true)}
sx={{ marginTop: 2, background: "white", color: "black" }}>
Edit Profile



























setShowLogin(false)} />

);
};
< /code>
Страница профиля имеет модал редактирования, который редактирует данные профиля и хранит их в бэкэнд. < /p>
modal < /p>
export const EditProfileModal = (props: any) => {
const { userRef, setUserDbData } = usePostUserProfileToDb();
const { userStorageData, setUserStorageData } = usePostUserProfileToStorage();
const { userProfile, setUserProfile } = useGetUserProfile();

const [profile, setProfile] = useState({
username: "",
bio: "",
gender: "",
sexo: "",
edu: "",
drinking: "",
smoking: "",
dob: "",
});

useEffect(() => {
if (userProfile) {
setProfile(userProfile);
}
}, [userProfile, setUserProfile]);

const handleSubmit = async (e: any) => {
e.preventDefault();
try {
setUserStorageData(profile);
setUserDbData(profile);
props.close();
} finally {
setIsSubmitting(false);
}
};
< /code>
И вот контекст.import React, { createContext, useState, useContext } from 'react';

const UserProfileContext = createContext(null);

export const UserProfileProvider = ({ children }) => {
const [userProfileContext, setUserProfileContext] = useState(null);

return (

{children}

);
};

export const useUserProfile = () => {
const context = useContext(UserProfileContext);
if (!context) {
throw new Error('useUserProfile must be used within a UserProfileProvider');
}
return context;
};
< /code>
Когда я пытаюсь установить контекст в крючке, я получаю следующую ошибку: < /p>

This expression is not callable.
Type 'never' has no call signatures.
< /code>
< /blockquote>
import { useEffect, useState } from "react";
import useGetUserId from "./useGetUserId";
import { app } from "../environments/environment";
import { doc, getDoc, getFirestore } from "firebase/firestore";
import { useUserProfile } from "../Context/UserProfileContext";

const useGetUserProfile = () => {
type profile = {
email: string;
username: string;
userBio: string;
dob: Date;
gender: string;
sexo: string;
education: string;
drinkingHabits: string;
smokingHabits: string;
};

const db = getFirestore(app);
const userId: string | null = useGetUserId();
const [isLoading, setIsLoading] = useState(true);
const [userProfile, setUserProfile] = useState(null);
const { userProfileContext, setUserProfileContext } = useUserProfile()

useEffect(() => {
const userProfile = async () => {
setIsLoading(true);
try {
const userRef = localStorage.getItem("PROFILE_INFO");
if (userRef) {
const profile: profile = JSON.parse(userRef);
setUserProfile(profile);
setUserProfileContext(profile)
} else {
if (userId) {
const id = JSON.parse(userId);
const userRef = await getDoc(doc(db, "users", id.user.uid));
if (userRef.exists()) {
const profile = userRef.data();
setUserProfile(profile);
}
}
}
} catch (error) {
console.log("error", error);
} finally {
setIsLoading(false);
}
};
userProfile();
}, [setUserProfile]);
return {
isLoading,
userProfile, setUserProfile
};
};

export default useGetUserProfile;
< /code>
Так что я не уверен, что делаю не так. Где именно устанавливается значение контекста, только у детей? От контекста детей, вы получаете данные профиля с крючков, а затем устанавливаете их, или вы устанавливаете данные контекста в крючках?


Подробнее здесь: https://stackoverflow.com/questions/794 ... ct-context
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»