jerem_d

Untitled

Oct 3rd, 2021
32
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useEffect, useRef } from "react";
  2. import { createContext } from "react";
  3. import * as api from "../../services/api";
  4. import { useQuery } from "react-query";
  5. import io from "socket.io-client";
  6.  
  7. const ChatContext = createContext();
  8.  
  9. const ChatProvider = ({ children }) => {
  10.   const [state, setState] = useState({ message: "", name: "", room: "général" });
  11.   const [chatLogs, setChatLogs] = useState([]);
  12.   const socketRef = useRef();
  13.  
  14.   useQuery("getUser", () => api.getUser(), {
  15.     onSuccess: (data) => {
  16.       setState({ ...state, name: data.data.pseudo });
  17.     },
  18.   });
  19.  
  20.   useEffect(() => {
  21.     socketRef.current = io.connect("http://localhost:4000");
  22.     return () => socketRef.current.disconnect();
  23.   }, []);
  24.  
  25.   useEffect(() => {
  26.     socketRef.current.on("message", ({ name, message }) => {
  27.       setChatLogs([...chatLogs, { name, message, room: state.room }]);
  28.     });
  29.   }, [chatLogs, state.room]);
  30.  
  31.   useEffect(() => {
  32.     socketRef.current.emit("room", {
  33.       room: state.room,
  34.     });
  35.  
  36.     return () =>
  37.       socketRef.current.emit("leave room", {
  38.         room: state.room,
  39.       });
  40.   }, [state.room]);
  41.  
  42.   const onTextChange = (e) => {
  43.     setState({ ...state, [e.target.name]: e.target.value });
  44.   };
  45.  
  46.   const onMessageSubmit = (e) => {
  47.     e.preventDefault();
  48.     const { name, message, room } = state;
  49.     socketRef.current.emit("message", { name, message, room });
  50.     setState({ message: "", name, room });
  51.   };
  52.  
  53.   return (
  54.     <ChatContext.Provider value={{ chatLogs, onTextChange, onMessageSubmit, state, setState }}>
  55.       {children}
  56.     </ChatContext.Provider>
  57.   );
  58. };
  59. export { ChatProvider, ChatContext };
  60.  
RAW Paste Data