Я создал приложение, которое хранит информацию пользователя в 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
Где установлено контекстное состояние в контексте реагирования? ⇐ Javascript
Форум по Javascript
-
Anonymous
1738953671
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>
Так что я не уверен, что делаю не так. Где именно устанавливается значение контекста, только у детей? От контекста детей, вы получаете данные профиля с крючков, а затем устанавливаете их, или вы устанавливаете данные контекста в крючках?
Подробнее здесь: [url]https://stackoverflow.com/questions/79421797/where-is-the-context-state-set-in-react-context[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия