Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

when user adds mk its info displays in theirs profile and i need that person can delete…

  1. User

    when user adds mk its info displays in theirs profile and i need that person can delete it import { Text, View, Image, ScrollView, Pressable } from 'react-native'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { gStyle } from '../styles/style'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native';

    export default function Profile() { const navigation = useNavigation(); const options = { day: 'numeric', month: 'long', hour: 'numeric', minute: 'numeric' }; const [userId, setUserId]=useState(null); const [userData, setUserData] = useState(null); const [bookedMK, setBookedMK] = useState([]); useEffect(()=>{ const unsubscribe=firebase.auth().onAuthStateChanged((user)=>{ if(user){ setUserId(user.uid); }else{ setUserId(null); } }); return()=>unsubscribe(); },[]) useEffect(() => { if(userId){ const userRef=firebase.database().ref(users/${userId}); userRef.on('value', snapshot=>{ const data = snapshot.val(); setUserData(data); }); const bookedMKRef = firebase.database().ref(users/${userId}/bookedMK); bookedMKRef.on('value', snapshot => { const data = snapshot.val(); if (data) { const mk = Object.values(data); setBookedMK([]); setBookedMK(mk) } else { setBookedMK([]); } });

            // Cleanup function which will remove the listeners when the component is unmounted
            return () => {
                userRef.off();
                bookedMKRef.off();
                
    

    }; }

    },[userId]);
        const handleLogOut = async () => {
            try {
            await firebase.auth().signOut();
            navigation.navigate('Auth');
            } catch (error) {
            console.error(error);
            }
            };
    

    return ( {userData?.name}, Добро пожаловать в{'\n'}личный кабинет Имя {userData?.name} Фамилия {userData?.surname} Электронная почта {userData?.email} Номер телефона {userData?.phone} Выйти Забронированные{'\n'}мастер-классы {bookedMK.map((mk, index)=>( {mk.name} {new Date(mk.time?.seconds * 1000).toLocaleTimeString([], options)} Цена: {mk.price} Р. ))}

            <Text style={gStyle.ProfileLine}></Text>
        </View>
    </View>
    <Footer/>
    </ScrollView>
            </View>
    

    ); }

  2. Assistant

    To allow the user to delete a booked MK, you can add a button or icon next to each booked MK item, and attach a function to it that will remove the item from the "bookedMK" array in the user's data.

    Here's an example:

    1. Modify the user data state to include the index of the booked MK item, to easily remove it later:
    const [userData, setUserData] = useState(null);
    const [bookedMK, setBookedMK] = useState([]);
    
    ...
    
    // When getting the booked MK data, set the index as well
    const mk = Object.entries(data).map(([index, mk]) => ({...mk, index}));
    setBookedMK(mk)
    
    ...
    
    
    1. Add a button or icon next to each booked MK item in the "ProfilePaidMK" section, and attach a function to it that will remove the item from the user's data:
    {bookedMK.map((mk, index) => (
      <View key={index} style={gStyle.ProfileDetails}>
        <Image source={{ uri: mk.image }} style={gStyle.ProfileImg} />
        <View style={gStyle.ProfileDescription}>
          <Text style={gStyle.ProfileTitleOfMK}>{mk.name}</Text>
          <Text style={gStyle.ProfileDate}>{new Date(mk.time?.seconds * 1000).toLocaleTimeString([], options)}</Text>
          <Text style={gStyle.ProfilePrice}>Цена: {mk.price} Р.</Text>
          <Pressable style={gStyle.deleteBtn} onPress={() => handleDeleteMK(mk.index)}>
            <Text style={gStyle.deleteBtnText}>Убрать</Text>
          </Pressable>
        </View>
      </View>
    ))}
    
    1. Implement the "handleDeleteMK" function, which will remove the booked MK item from the user's data:
    const handleDeleteMK = (mkIndex) => {
      if (!userId) return;
      const userRef = firebase.database().ref(`users/${userId}/bookedMK/${mkIndex}`);
      userRef.remove().then(() => {
        // Update the bookedMK state to reflect the updated list
        const updatedBookedMK = bookedMK.filter(mk => mk.index !== mkIndex);
        setBookedMK(updatedBookedMK);
      }).catch((error) => {
        console.error(error);
      });
    }
    

    This function will remove the MK item with the given index from the "bookedMK" object in the user's data, and then update the "bookedMK" state to reflect the updated list.

  3. User

    can i do that all bookedMK was just like a component?

  4. Assistant

    Yes, you can create a separate component for the booked MK items and render it in your Profile component for each booked MK entry. Here's an example:

    1. Create a new component, let's call it "BookedMKItem", that will receive a single booked MK item as a prop:
    import React from 'react';
    import { Text, View, Image, Pressable } from 'react-native';
    import { gStyle } from '../styles/style';
    import { firebase } from '../Firebase/firebase';
    
    const options = { day: 'numeric', month: 'long', hour: 'numeric', minute: 'numeric' };
    
    export default function BookedMKItem(props) {
      const { mk, userId, onDelete } = props;
    
      const handleDeleteMK = () => {
        const userRef = firebase.database().ref(`users/${userId}/bookedMK/${mk.index}`);
        userRef.remove().then(() => {
          onDelete(mk.index);
        }).catch((error) => {
          console.error(error);
        });
      }
    
      return (
        <View style={gStyle.ProfileDetails}>
          <Image source={{ uri: mk.image }} style={gStyle.ProfileImg} />
          <View style={gStyle.ProfileDescription}>
            <Text style={gStyle.ProfileTitleOfMK}>{mk.name}</Text>
            <Text style={gStyle.ProfileDate}>{new Date(mk.time?.seconds * 1000).toLocaleTimeString([], options)}</Text>
            <Text style={gStyle.ProfilePrice}>Цена: {mk.price} Р.</Text>
            <Pressable style={gStyle.deleteBtn} onPress={handleDeleteMK}>
              <Text style={gStyle.deleteBtnText}>Убрать</Text>
            </Pressable>
          </View>
        </View>
      );
    }
    

    This component will render a single booked MK item, including an "Убрать" (remove) button that will call the "handleDeleteMK" function to remove the item from the user's data.

    1. In your Profile component, replace the "bookedMK.map" block with a rendering of the "BookedMKItem" component for each booked MK item:
    import React, { useState, useEffect } from 'react';
    import { Text, View, Image, ScrollView } from 'react-native';
    import Header from '../components/Header';
    import Footer from '../components/Footer';
    import BookedMKItem from '../components/BookedMKItem';
    import { gStyle } from '../styles/style';
    import { firebase } from '../Firebase/firebase';
    
    export default function Profile() {
      const [userId, setUserId] = useState(null);
      const [userData, setUserData] = useState(null);
      const [bookedMK, setBookedMK] = useState([]);
    
      useEffect(() => {
        const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
          if (user) {
            setUserId(user.uid);
          } else {
            setUserId(null);
          }
        });
        return () => unsubscribe();
      }, []);
    
      useEffect(() => {
        if (userId) {
          const userRef = firebase.database().ref(`users/${userId}`);
          userRef.on('value', (snapshot) => {
            const data = snapshot.val();
            setUserData(data);
          });
    
          const bookedMKRef = firebase.database().ref(`users/${userId}/bookedMK`);
          bookedMKRef.on('value', (snapshot) => {
            const data = snapshot.val();
            if (data) {
              const mk = Object.entries(data).map(([index, mk]) => ({ ...mk, index }));
              setBookedMK(mk);
            } else {
              setBookedMK([]);
            }
          });
    
          // Cleanup function which will remove the listeners when the component is unmounted
          return () => {
            userRef.off();
            bookedMKRef.off();
          };
        }
      }, [userId]);
    
      const handleDeleteMK = (mkIndex) => {
        const updatedBookedMK = bookedMK.filter(mk => mk.index !== mkIndex);
        setBookedMK(updatedBookedMK);
      }
    
      const handleLogOut = async () => {
        try {
          await firebase.auth().signOut();
          navigation.navigate('Auth');
        } catch (error) {
          console.error(error);
        }
      };
    
      return (
        <ScrollView>
          <Header />
          <View style={gStyle.main}>
            <View style={gStyle.ProfileBox}>
              <View style={gStyle.ProfileGreeting}>
                <Text style={gStyle.ProfileName}>{userData?.name},</Text>
                <Text style={gStyle.ProfileHello}>Добро пожаловать в{'\n'}личный кабинет</Text>
              </View>
              <View style={gStyle.ProfileBlock}>
                <View style={gStyle.ProfileChain}>
                  <Text style={gStyle.ProfileTitle}>Имя</Text>
                  <View style={gStyle.ProfileInfo}>
                    <Text style={gStyle.ProfileValue}>{userData?.name}</Text>
                  </View>
                </View>
                <View style={gStyle.ProfileChain}>
                  <Text style={gStyle.ProfileTitle}>Фамилия</Text>
                  <View style={gStyle.ProfileInfo}>
                    <Text style={gStyle.ProfileValue}>{userData?.surname}</Text>
                  </View>
                </View>
                <View style={gStyle.ProfileChain}>
                  <Text style={gStyle.ProfileTitle}>Электронная почта</Text>
                  <View style={gStyle.ProfileInfo}>
                    <Text style={gStyle.ProfileValue}>{userData?.email}</Text>
                  </View>
                </View>
                <View style={gStyle.ProfileChain}>
                  <Text style={gStyle.ProfileTitle}>Номер телефона</Text>
                  <View style={gStyle.ProfileInfo}>
                    <Text style={gStyle.ProfileValue}>{userData?.phone}</Text>
                  </View>
                </View>
                <Pressable style={gStyle.logout} onPress={handleLogOut}>
                  <Text style={gStyle.gobacktxt}>Выйти</Text>
                </Pressable>
              </View>
            </View>
            <View style={gStyle.ProfilePaidMK}>
              <Text style={gStyle.ProfilePaid}>Забронированные{'\n'}мастер-классы</Text>
              <Text style={gStyle.ProfileLine}></Text>
              {bookedMK.map((mk) => (
                <BookedMKItem
                  key={mk.index}
                  mk={mk}
                  userId={userId}
                  onDelete={handleDeleteMK}
                />
              ))}
              <Text style={gStyle.ProfileLine}></Text>
            </View>
          </View>
          <Footer />
        </ScrollView>
      );
    }
    

    Note that we pass the booked MK item, the user ID, and a function to handle the delete event as props to the "BookedMKItem" component. Also note that we've refactored the "bookedMK.map" block to render the "BookedMKItem" component instead. The "handleDeleteMK" function has also been modified to remove the item from the state.

    With these changes, you'll now have a separate component to handle each booked MK item, and the Profile component will simply render these dynamically based on the data in each user's "bookedMK" object.