Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

вот Header.js import React from "react"; import { NavLink } from "react-router-dom";…

  1. User

    вот Header.js

    import React from "react"; import { NavLink } from "react-router-dom"; import { db } from "../firebase"; import { doc, getDoc } from "firebase/firestore";

    import { ReactComponent as UserIcon } from "../images/icons/user.svg"; import LevelIcon from "../images/icons/LvlIcon";

    const Header = () => { return ( sch1z0o Claim ); };

    export default Header;

    вот collection из firestore: Document ID balance battery energy firstName freeGuru fullTank lastName level refBonus refereeId referrals tapBalance tapValue timeRefill timeSta timeStaTank totalBalance userId username 381700637 9999 {level: 1, energy: 500} 500 "Ziper" 3 3 "Lin" {name: "Warm", imgUrl: "/warm.webp", imgTap: "/coin-1.webp", imgBoost: "/coins-1.webp", id: 1} 0 null [] 0 {value: 1, level: 1} {level: 1, step: 600, duration: 10} null null "00" "381700637" "ziperlin"

    я хочу чтобы в Header отображалось имя пользователя, который использует приложение. Т.е. не sch1z0o, а Ziper Lin

    вот для примера отрывок из App.js, чтобы ты понял как установить активного пользователя

    function App() { const { energy, setEnergy, displayEnergy, setDisplayEnergy, idme, setIdme, count, setCount } = useContext(EnergyContext); // eslint-disable-next-line const [username, setUsername] = useState(""); // eslint-disable-next-line const [name, setName] = useState(""); const imageRef = useRef(null); const [clicks, setClicks] = useState([]); const [loading, setLoading] = useState(true); const [showLevels, setShowLevels] = useState(false);

    const levelsAction = () => { setShowLevels(true); document.getElementById("footermain").style.zIndex = "50"; };

    const handleClick = (e) => { if (energy > 0) { const { offsetX, offsetY, target } = e.nativeEvent; const { clientWidth, clientHeight } = target;

      const horizontalMidpoint = clientWidth / 2;
      const verticalMidpoint = clientHeight / 2;
    
      const animationClass =
        offsetX < horizontalMidpoint
          ? "wobble-left"
          : offsetX > horizontalMidpoint
          ? "wobble-right"
          : offsetY < verticalMidpoint
          ? "wobble-top"
          : "wobble-bottom";
    
      // Remove previous animations
      imageRef.current.classList.remove(
        "wobble-top",
        "wobble-bottom",
        "wobble-left",
        "wobble-right"
      );
    
      // Add the new animation class
      imageRef.current.classList.add(animationClass);
    
      // Remove the animation class after animation ends to allow re-animation on the same side
      setTimeout(() => {
        imageRef.current.classList.remove(animationClass);
      }, 500); // duration should match the animation duration in CSS
    
      // Increment the count
      const rect = e.target.getBoundingClientRect();
      const newClick = {
        id: Date.now(), // Unique identifier
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
      };
    
      const updatedCount = count + 2; // Increment count by 5
      const updatedEnergy = energy - 2;
    
      setClicks((prevClicks) => [...prevClicks, newClick]);
      setCount(updatedCount);
      setEnergy(updatedEnergy);
      setDisplayEnergy(updatedEnergy); // Update display energy
    
      updateUserStatsInFirestore(idme, updatedCount, updatedEnergy);
    
      // Remove the click after the animation duration
      setTimeout(() => {
        setClicks((prevClicks) =>
          prevClicks.filter((click) => click.id !== newClick.id)
        );
      }, 1000); // Match this duration with the animation duration
    }
    

    };

    useEffect(() => { // Fetch username and user ID from Telegram Web App context const telegramName = window.Telegram.WebApp.initDataUnsafe?.user?.first_name; const telegramLastName = window.Telegram.WebApp.initDataUnsafe?.user?.last_name; const telegramUsername = window.Telegram.WebApp.initDataUnsafe?.user?.username; const telegramUserid = window.Telegram.WebApp.initDataUnsafe?.user?.id;

    if (telegramName) {
      setName(telegramName + " " + telegramLastName);
    }
    
    if (telegramUsername) {
      setUsername(telegramUsername);
    }
    if (telegramUserid) {
      setIdme(telegramUserid);
    }
    
    if (telegramUsername && telegramUserid) {
      saveRefereeIdToFirestore();
    }
    
    // Fetch count and energy from Firestore when component mounts
    if (telegramUserid) {
      fetchUserStatsFromFirestore(telegramUserid)
        .then((userStats) => {
          if (isNaN(userStats.count)) {
            setCount(0);
            updateUserStatsInFirestore(telegramUserid, 0, 500);
          } else {
            setCount(userStats.count);
            setEnergy(userStats.energy);
            setDisplayEnergy(userStats.energy); // Update display energy
          }
          setLoading(false); // Set loading to false after fetching count
        })
        .catch(() => {
          setCount(0); // Set count to 0 if fetching fails
          setEnergy(500); // Set energy to 500 if fetching fails
          setLoading(false);
        });
    }
    // eslint-disable-next-line
    

    }, []);

  2. Assistant

    To display the user's name (for example, "Ziper Lin") in the Header component instead of the hardcoded "sch1z0o", you need to fetch the user's data from Firestore and update the component state accordingly. Since the current user's ID (idme) is retrieved in App.js, you can use React context or props to pass this information down to the Header component and fetch the corresponding user data from Firestore.

    Here's how you can achieve this:

    1. Set Up Context or Prop Passing: Make sure the idme and potentially the user's full name are accessible by the Header component. This can be done via context or prop drilling from App.js.

    2. Fetch User Data in Header Component: Modify the Header component to fetch and display the user's name based on idme.

    Here's an example using context:

    Step 1: Update Your Context

    Ensure idme is part of a context that is accessible to Header.

    // EnergyContext.js (or your existing context file)
    import React, { createContext, useState } from 'react';
    
    export const EnergyContext = createContext();
    
    export const EnergyProvider = ({ children }) => {
      const [idme, setIdme] = useState(null);
      // Include other states you need like energy, setEnergy, etc.
    
      return (
        <EnergyContext.Provider value={{ idme, setIdme /* other values */ }}>
          {children}
        </EnergyContext.Provider>
      );
    };
    

    Step 2: Modify App.js to Use Context

    Ensure App.js consumes and provides the context. Make sure you're wrapping your main component tree with this provider somewhere, usually at the top level like index.js or App.js.

    // App.js
    import React, { useContext, useEffect } from 'react';
    import { EnergyContext } from './EnergyContext';
    
    function App() {
      const { idme, setIdme } = useContext(EnergyContext);
      // Other hooks and logic remain the same
    
      useEffect(() => {
        // Set idme here based on Telegram API
        const telegramUserid = window.Telegram.WebApp.initDataUnsafe?.user?.id;
        if (telegramUserid) {
          setIdme(telegramUserid);
        }
      }, []);
      // Rest of your App logic
    }
    
    export default App;
    

    Step 3: Access and Use Context in Header

    Finally, in the Header component, use the useEffect hook to fetch user data when idme is available.

    // Header.js
    import React, { useContext, useEffect, useState } from 'react';
    import { NavLink } from "react-router-dom";
    import { db } from "../firebase";
    import { doc, getDoc } from "firebase/firestore";
    import { EnergyContext } from './EnergyContext'; // Adjust the import path accordingly
    import { ReactComponent as UserIcon } from "../images/icons/user.svg";
    import LevelIcon from "../images/icons/LvlIcon";
    
    const Header = () => {
        const { idme } = useContext(EnergyContext); 
        const [fullname, setFullname] = useState("");
    
        useEffect(() => {
            if (idme) {
                const fetchUserData = async () => {
                    try {
                        const userDoc = await getDoc(doc(db, "users", idme)); // assuming your collection is called "users"
                        if (userDoc.exists()) {
                            const data = userDoc.data();
                            setFullname(`${data.firstName} ${data.lastName}`);
                        }
                    } catch (error) {
                        console.error("Error fetching user data: ", error);
                    }
                };
                fetchUserData();
            }
        }, [idme]);
    
        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'>
                            {fullname || "Loading..."} {/* Handle default or loading state */}
                        </span>
                        <span className=' text-primary bg-background2 rounded-full absolute right-[-27px] top-[-10px] shadow-[0px_4px_4px_0px_#00000040]'>
                            <LevelIcon level={5} 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;
    

    In this setup, the Header component fetches the full name from Firestore based on the user ID (idme) and displays it. You should ensure that the Firestore collection and document IDs are correctly referenced. Adjust collection names and field names based on your Firestore setup.