dimanche 23 juillet 2023

save a created random number in state and keep it as it is Reactjs

I created a chat application and allowed the user to create a chat room at any time with a name chosen by the user, and every time the user typed the name of the same room, the application will enter him in the same chat that he did before,

and I created a function that generates a random number for the room that is generated, but even if I write the name of the same room, it generates a different number for the same room,

how do I keep the number that was created the first time for the room?

this is app.js code:

import './style.scss';
import Register from "./pages/Register.jsx";
import Login from './pages/Login';
import { Home } from './pages/Home';
import { Auth } from './components/Auth';
import { useState, useRef } from 'react';
import Cookies from "universal-cookie";
import Chat from './components/Chat';
import {auth} from "./firebase";
import { signOut } from "firebase/auth";
import randomString from 'random-string';
const cookies = new Cookies();

function App() {
  const [isAuth, setIsAuth] = useState(cookies.get("auth-token"));
  const [room, setRoom] = useState(null);

  const roomInputRef = useRef(null)

  var x = randomString({
    length: 8,
    numeric: true,
    letters: false,
    special: false,
    
    });

  const signUserOut = async() => {
    await signOut(auth)
    cookies.remove("auth-token")
    setIsAuth(false)
    setRoom(null)
  }

    if (!isAuth) {
    return (
      <div className="App">
        <Auth setIsAuth={setIsAuth}/>
      </div>
    );
  }

  return (
  <>
    {room? (
      <Chat room={room} setRoom={setRoom} x={x}/>
        ) : (
          <div className='room'> 
            <label>Enter room name:</label>
            <input ref={roomInputRef}/>
              <button onClick={() => [randomString(),setRoom(roomInputRef.current.value)]}>
                Enter chat
              </button>
          </div>
        )
      }

      <div className='sign-out'>
        <button onClick={signUserOut}> logout </button>
      </div>

    </>
    )
}

export default App;

this is Chat.jsx code:

import { useEffect, useState } from "react";
import { addDoc, collection, serverTimestamp, onSnapshot, query, where, orderBy } from "firebase/firestore";
import { auth, db } from "../firebase";
import "../styles/Chat.css";


const Chat = (props) => {
  const {room, setRoom, x} = props
  const [newMessage, setNewMessage] = useState("");
  const [messages, setMessages] = useState([]);

  const messagesRef = collection(db, "messages");

  useEffect(()=>{
    const queryMessages = query(
      messagesRef, 
      where("room", "==", room), 
      orderBy("createdAt")
      );
    const unsubscribe = onSnapshot(queryMessages, (snapshot)=>{
      let messages = [];
      snapshot.forEach((doc) => {
        messages.push({ ...doc.data(), id: doc.id })
      });
      setMessages(messages)
    });

    return () => unsubscribe();
  },[])

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (newMessage === "") return;

    await addDoc(messagesRef, {
      text: newMessage,
      createdAt: serverTimestamp(),
      user: auth.currentUser.displayName,
      room,
    });

    setNewMessage("")
  };

  const roomExit = () => {
    setRoom(null)
  }

  return (
    <div className='Chat'>
      <div className="header">
        <h1> Welcome to: {room} number: {x} </h1>
      </div>
      <div className="messages">
        {messages.map((message) => (
        <div className="message" key={message.id}>
          <span className="user"> {message.user} </span>
          {message.text}
        </div>
        ))}
        </div>
      <form onSubmit={handleSubmit} className="new-message-form">
        <input 
        className="new-message-input" 
        placeholder="Type your message here..."
        onChange={(e) => setNewMessage(e.target.value)}
        value={newMessage}
        />
        <button type="submit" className="send-button">Send</button>
      </form>
      <button onClick={roomExit}>change room</button>
    </div>
  )
}

export default Chat



Aucun commentaire:

Enregistrer un commentaire