socketio / socket.io

Realtime application framework (Node.JS server)
https://socket.io
MIT License
61.3k stars 10.13k forks source link

Not able to pass prop socket #4944

Closed utkarsh-1602 closed 8 months ago

utkarsh-1602 commented 10 months ago

Discussed in https://github.com/socketio/socket.io/discussions/4943

Originally posted by **utkarsh-1602** February 8, 2024 This is my App.jsx ``` import React, { Fragment } from 'react'; import { Provider } from 'react-redux'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import decode from 'jwt-decode'; import { store } from '../store'; import { setToken, setCurrentUser, addError } from '../store/actions'; import NavBar from './NavBar'; import RouteViews from './RouteViews'; import socketIO from 'socket.io-client'; import Home from '../components/HomeChat'; import ChatPage from '../components/ChatPage'; const socket = socketIO.connect('http://localhost:4000'); console.log("Socket: ", socket); // The code checks if there is a JWT token stored in the local storage if (localStorage.jwtToken) { setToken(localStorage.jwtToken); // If a token exists, it sets the token in the Redux store using the setToken action creator. try { store.dispatch(setCurrentUser(decode(localStorage.jwtToken))); // if token is present, then it attempts to decode the token } catch (err) { store.dispatch(setCurrentUser({})); // If decoding is successful, it dispatches the setCurrentUser action with the decoded user data to set the current user in the Redux store. store.dispatch(addError(err)); // If decoding fails, it dispatches the setCurrentUser action with an empty object and adds an error to the Redux store using the addError action creator. } } const App = () => ( }> ); export default App; ``` This is my ChatPage.jsx ``` import React from 'react'; import ChatBar from '../components/ChatBar'; import ChatBody from '../components/ChatBody'; import ChatFooter from '../components/ChatFooter'; import { Redirect } from 'react-router-dom/cjs/react-router-dom.min'; const ChatPage = ({ socket, isAuthenticated }) => { if (!isAuthenticated) return ; console.log("CHATPAGE SOCKET===> ", socket) return (
); }; export default ChatPage; ``` here the socket is `undefined` when I do console.log
darrachequesne commented 9 months ago

Hi! I think it will be easier to put the socket object in its own file, which can then be imported in the components.

Reference: https://socket.io/how-to/use-with-react

darrachequesne commented 8 months ago

I think this can be closed now. Please reopen if needed.