я хочу чтобы в Header отображалось имя пользователя, который использует приложение. Т.е. не sch1z0o, а Ziper Lin
проблема в том, что получение данных о текущем пользователе должно происходить с помощью telegram webapp и я не знаю как это сделать
вот userContext.js
import React, { createContext, useContext, useState, useEffect, useRef, useCallback } from 'react';
import { doc, getDoc, setDoc, updateDoc, arrayUnion, getDocs, collection } from 'firebase/firestore';
import { db } from '../firebase'; // Adjust the path as needed
import { disableReactDevTools } from '@fvilers/disable-react-devtools';
if (process.env.NODE_ENV === 'production') {
disableReactDevTools();
}
import React from "react";
import { NavLink } from "react-router-dom";
import { useUser } from '../context/userContext'; // Replace with actual path
import { ReactComponent as UserIcon } from "../images/icons/user.svg";
import LevelIcon from "../images/icons/LvlIcon";
const refillIntervalRef = useRef(null);
const accumulatedEnergyRef = useRef(energy);
const [isRefilling, setIsRefilling] = useState(false);
const refillDuration = timeRefill.duration * 60 * 1000; // 2 minutes in milliseconds
const refillSteps = timeRefill.step; // Number of increments
const incrementValue = refiller / refillSteps; // Amount to increment each step
const defaultEnergy = refiller; // Default energy value
const refillEnergy = () => {
if (isRefilling) return;
setIsRefilling(true);
refillIntervalRef.current = setInterval(() => {
setEnergy((prevEnergy) => {
if (isNaN(prevEnergy) || prevEnergy >= refiller) {
clearInterval(refillIntervalRef.current);
setIsRefilling(false);
return refiller;
}
const newEnergy = Math.min(prevEnergy + incrementValue, refiller); // Ensure energy doesn't exceed max
if (!isNaN(newEnergy)) {
accumulatedEnergyRef.current = newEnergy;
localStorage.setItem('energy', newEnergy); // Save updated energy to local storage
localStorage.setItem('lastRefillTime', Date.now()); // Save the current time
console.log('Energy saved to local storage:', newEnergy); // Log the energy value saved to local storage
}
return newEnergy;
});
}, refillDuration / refillSteps); // Increase energy at each step
if (userDoc.exists()) {
const userData = userDoc.data();
const lastDate = userData.timeSta.toDate(); // Convert Firestore timestamp to JS Date
const formattedDates = lastDate.toISOString().split('T')[0]; // Get the date part in YYYY-MM-DD format
const currentDate = new Date(); // Get the current date
const formattedCurrentDates = currentDate.toISOString().split('T')[0]; // Get the date part in YYYY-MM-DD format
// const timeDifference = (currentTime - lastTimeSta) / 1000; // Time difference in seconds
// console.log('timesta is:', lastDate)
// console.log('current time is:', currentDate)
// console.log('time difference is:', timeDifference)
if (formattedDates !== formattedCurrentDates && userData.freeGuru <= 0) {
await updateDoc(userRef, {
freeGuru: 3,
timeSta: new Date()
});
setFreeGuru(3);
}
}
if (userDoc.exists()) {
const userData = userDoc.data();
const lastDateTank = userData.timeStaTank.toDate(); // Convert Firestore timestamp to JS Date
const formattedDate = lastDateTank.toISOString().split('T')[0]; // Get the date part in YYYY-MM-DD format
const currentDate = new Date(); // Get the current date
const formattedCurrentDate = currentDate.toISOString().split('T')[0]; // Get the date part in YYYY-MM-DD format
// const timeDifference = (currentTime - lastTimeSta) / 1000; // Time difference in seconds
console.log('timesta is:', lastDateTank)
console.log('formated timesta is:', formattedDate)
console.log('current time is:', currentDate)
console.log('formatted current time is:', formattedCurrentDate)
// console.log('time difference is:', timeDifference)
if (formattedDate !== formattedCurrentDate && userData.fullTank <= 0) {
await updateDoc(userRef, {
fullTank: 3,
timeStaTank: new Date()
});
setFullTank(3);
}
}
};
useEffect(() => {
// Fetch the remaining clicks from Firestore when the component mounts
const fetchRemainingClicks = async () => {
if (id) {
const userRef = doc(db, 'telegramUsers', id.toString());
const userDoc = await getDoc(userRef);
if (userDoc.exists()) {
const userData = userDoc.data();
setFreeGuru(userData.freeGuru || 0);
setFullTank(userData.fullTank || 0);
}
}
};
const fetchAllUsers = async () => {
try {
const userRef = collection(db, "telegramUsers");
const querySnapshot = await getDocs(userRef);
const allUsers = [];
const uniqueUsernames = new Set(); // Using a Set to store unique usernames
querySnapshot.forEach((doc) => {
const data = doc.data();
const username = data.username;
const firstName = data.firstName;
const refereeId = data.refereeId;
const balance = data.balance;
// Check if the username is unique, if yes, add it to the allUsers array and set
// a flag indicating that it has been added
if (!uniqueUsernames.has(username)) {
allUsers.push({ username, firstName, refereeId, balance });
uniqueUsernames.add(username);
}
});
setUsers(allUsers.length);
setDividedUsers(allUsers.length / 2);
setLoading(false); // Set loading to false once data is fetched
// Update the count of unique users
} catch (error) {
console.error("Error fetching users: ", error);
setLoading(false); // Set loading to false if there's an error
}
// Call this function when appropriate, such as on component mount or before handleClick
useEffect(() => {
if (id) {
checkAndUpdateFreeGuru();
checkAndUpdateFullTank();
}
// eslint-disable-next-line
}, [id]);
useEffect(() => {
if (id) {
updateUserLevel(id, tapBalance);
To integrate user data from the Telegram WebApp into your Header component, you can follow these steps. You'll be fetching and displaying the user's name dynamically from Firestore based on the Telegram user information.
First, make sure you have userContext.js properly set up to handle the Telegram user data, which it seems you do. You have the user's information being fetched and saved into the state.
Step-by-step Implementation
Extract User Information:
Ensure that you are obtaining your user's firstName and lastName from the Firestore data and then setting it in the context state.
Update the Header.js to Use Context:
Modify your Header component to consume the UserContext to pull the user data.
Update the Context Provider:
Ensure the user data is updated and set correctly when fetched from Firestore, which seems to be done in the sendUserData function.
Context Usage: Ensure that the useUser hook is correctly pulling the user data (e.g., name and level) from the context provider.
Initial States: If the data loading isn't instantaneous, you might want to provide fallback text like 'Loading...'.
Error Handling: Implement error handling in the user's data fetching (sendUserData function) to cope with failures in retrieving user data.
User Data Population: The integration with Telegram should trigger the sendUserData fetch only once, ideally when the component mounts.
This setup should ensure that your Header dynamically displays the user's full name obtained through Telegram WebApp integration. Adjust the path for userContext import to fit your project structure.
Header.js:8 Uncaught TypeError: Cannot destructure property 'name' of '(0 , context_userContext__WEBPACK_IMPORTED_MODULE_1_.useUser)(...)' as it is undefined.
at Header (Header.js:8:1)
at renderWithHooks (react-dom.development.js:16175:1)
at mountIndeterminateComponent (react-dom.development.js:20913:1)
at beginWork (react-dom.development.js:22416:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
at invokeGuardedCallback (react-dom.development.js:4274:1)
at beginWork1(react−dom.development.js:27405:1)atperformUnitOfWork(r1 @ react-dom.development.js:27405
performUnitOfWork @ react-dom.development.js:26513
workLoopSync @ react-dom.development.js:26422
renderRootSync @ react-dom.development.js:26390
performConcurrentWorkOnRoot @ react-dom.development.js:25694
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
Show 14 more frames
Show less
Header.js:8 Uncaught TypeError: Cannot destructure property 'name' of '(0 , context_userContext__WEBPACK_IMPORTED_MODULE_1_.useUser)(...)' as it is undefined.
at Header (Header.js:8:1)
at renderWithHooks (react-dom.development.js:16175:1)
at mountIndeterminateComponent (react-dom.development.js:20913:1)
at beginWork (react-dom.development.js:22416:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
at invokeGuardedCallback (react-dom.development.js:4274:1)
at beginWork1 @ react-dom.development.js:27405
performUnitOfWork @ react-dom.development.js:26513
workLoopSync @ react-dom.development.js:26422
renderRootSync @ react-dom.development.js:26390
recoverFromConcurrentError @ react-dom.development.js:25806
performConcurrentWorkOnRoot @ react-dom.development.js:25706
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
Show 15 more frames
Show less
react-dom.development.js:18572 The above error occurred in the component:
at Header (http://localhost:3000/frontend/static/js/bundle.js:843:68)
at div
at Home (http://localhost:3000/frontend/static/js/bundle.js:9360:51)
at RenderedRoute (http://localhost:3000/frontend/static/js/bundle.js:76357:5)
at RenderErrorBoundary (http://localhost:3000/frontend/static/js/bundle.js:76304:5)
at DataRoutes (http://localhost:3000/frontend/static/js/bundle.js:74924:5)
at Router (http://localhost:3000/frontend/static/js/bundle.js:76982:15)
at RouterProvider (http://localhost:3000/frontend/static/js/bundle.js:74711:5)
at TonConnectUIProvider (http://localhost:3000/frontend/static/js/bundle.js:99026:7)
React will try to recreate this component tree from scratch using the error boundary you provided, RenderErrorBoundary.
logCapturedError @ react-dom.development.js:18572
callback @ react-dom.development.js:18640
callCallback @ react-dom.development.js:13122
commitUpdateQueue @ react-dom.development.js:13143
commitLayoutEffectOnFiber @ react-dom.development.js:23263
commitLayoutMountEffects_complete @ react-dom.development.js:24578
commitLayoutEffects_begin @ react-dom.development.js:24564
commitLayoutEffects @ react-dom.development.js:24502
commitRootImpl @ react-dom.development.js:26779
commitRoot @ react-dom.development.js:26638
finishConcurrentRender @ react-dom.development.js:25848
performConcurrentWorkOnRoot @ react-dom.development.js:25765
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
Show 15 more frames
Show less
hooks.tsx:630 React Router caught the following error during render TypeError: Cannot destructure property 'name' of '(0 , context_userContext__WEBPACK_IMPORTED_MODULE_1_.useUser)(...)' as it is undefined.
at Header (Header.js:8:1)
at renderWithHooks (react-dom.development.js:16175:1)
at mountIndeterminateComponent (react-dom.development.js:20913:1)
at beginWork (react-dom.development.js:22416:1)
at beginWork$1 (react-dom.development.js:27381:1)
at performUnitOfWork (react-dom.development.js:26513:1)
at workLoopSync (react-dom.development.js:26422:1)
at renderRootSync (react-dom.development.js:26390:1)
at recoverFromConcurrentError (react-dom.development.js:25806:1)
at performConcurrentWorkOnRoot (react-dom.development.js:25706:1) {componentStack: '\n at Header (http://localhost:3000/frontend/sta…alhost:3000/frontend/static/js/bundle.js:99026:7)'}
The error you're encountering, Cannot destructure property 'name' of '(0 , _context_userContext__WEBPACK_IMPORTED_MODULE_1__.useUser)(...)' as it is undefined, usually suggests that the useUser hook is returning an undefined value, or your component is trying to consume the context provider before it's ready.
Let's address this step by step:
Step 1: Verify Context Setup
Make sure your UserContext.Provider is wrapping your application's components that need access to the context. The Header component must be inside this provider.
Step 2: Handle Undefined Context
Modify your Header.js to account for the scenario where the context might not be available immediately:
import React from "react";
import { NavLink } from "react-router-dom";
import { useUser } from '../context/userContext'; // Replace with actual path
import { ReactComponent as UserIcon } from "../images/icons/user.svg";
import LevelIcon from "../images/icons/LvlIcon";
const Header = () => {
const user = useUser();
if (!user) {
// Handle the case where user context is not yet set or failed to load
return <div>Loading...</div>;
}
const { name, level } = user;
return (
<section className='w-full flex items-center justify-between align-middle h-[80px] bg-cards flex-row gap-8 px-5 py-2'>
<NavLink to='/'>
<div className='flex items-center justify-between align-middle text-white py-1 px-2 rounded-md bg-background2 gap-2 pr-8 relative h-[36px] shadow-[0px_4px_4px_0px_#00000040]'>
<UserIcon />
<span className='font-Inter text-18.5 font-semibold text-left'>
{name || 'Loading...'}
</span>
<span className=' text-primary bg-background2 rounded-full absolute right-[-27px] top-[-10px] shadow-[0px_4px_4px_0px_#00000040]'>
<LevelIcon level={level?.id || 1} className='text-primary' />
</span>
</div>
</NavLink>
<NavLink to='/connect'>
<div className='flex items-center justify-between align-middle text-white py-1 px-2 rounded-md bg-background2 gap-2 h-[36px] shadow-[0px_4px_4px_0px_#00000040]'>
<span className='font-Inter text-18.5 font-semibold text-left'>
Claim
</span>
<UserIcon />
</div>
</NavLink>
</section>
);
};
export default Header;
Step 3: Check UserProvider
Ensure that the UserProvider component correctly initializes and provides the context. If you have any side effects or async operations in UserProvider, make sure the context is not attempting to be accessed before it is set.
Step 4: Debug Async Data Fetching
If your context data is being fetched asynchronously (e.g., from Firestore), ensure you handle loading states correctly within your UserProvider and components that rely on it. You can introduce a loading state in UserProvider and render these components only after the context is populated.
This setup should temporarily handle cases when the context data is not immediately available. You should adjust the handling according to your overall app architecture and initialization process.
};
export default Header;
кажется не удается получить контекст
If the "Loading..." message persists, it suggests that either the context is not being set correctly or it's not updating as expected. Here are some common points to check and troubleshoot why the context might not be providing the expected data:
Step 1: Verify Context Provider
Ensure that UserProvider is correctly wrapping your Header component in your application's component tree. The Header component needs to be a descendant of UserProvider.
// Example App.js or index.js
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import { UserProvider } from './context/userContext'; // Use the correct path
import Header from './components/Header'; // Use the correct path to your Header
function App() {
return (
<Router>
<UserProvider>
<Header />
{/* other components */}
</UserProvider>
</Router>
);
}
export default App;
Step 2: Check Initial State in UserProvider
Make sure that your UserProvider correctly initializes and updates state. Specifically, ensure that the state corresponding to the name and level is populated with user data.
Step 3: Debug Data Population in UserProvider
Add some logging inside your useEffect or async function in UserProvider to see if you're successfully fetching data from Firestore and setting it properly:
useEffect(() => {
const loadData = async () => {
// Add logging
console.log("Fetching user data...");
try {
// Your existing logic to fetch data
const userDoc = await getDoc(userRef);
if (userDoc.exists()) {
const userData = userDoc.data();
console.log('User data:', userData); // Log the fetched user data
setName(userData.firstName + " " + userData.lastName);
// Set other state as needed
}
} catch (error) {
console.error("Error fetching user data: ", error);
}
};
loadData();
}, []);
Step 4: Verify the Hook and Context
In your userContext.js, make sure the useUser hook is correctly returning the UserContext value:
Verify that the Telegram WebApp integration is working correctly to provide the necessary user data. If there's a fallback mechanism, make sure it behaves as expected and updates the state.
By following these steps and adding the suggested console logs, you should be able to identify why the Header is not getting the expected user data. Make sure to review each part of your data flow, from Telegram WebApp to Firestore, and finally to how it's being consumed in the Header.