I am currently working on an app that is using React, Redux, and Socket.io. When the user signs in and goes to the messaging page, the socket and room are created just like it should. However, when I click refresh, it seems like my useEffect function is firing before it receives the data from the redux store which the function set up the socket and room correctly. Has anyone ever had an issue like this? And if so how do you fix it? Thanks in advance
Edit: Just tried using a setTimeout() and still producing the same results. I am at a loss. Any help would be appreciated
Here is the code:
import Sidebar from './Sidebar';
import { Container, Col, Row, Card } from 'react-bootstrap';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { receiveMessage } from '../../actions/conversation';
//Socket.IO import
import io from 'socket.io-client';
const Messenger = ({ auth, receiveMessage }) => {
const [socket, setSocket] = useState(null);
const setupSocket = () => {
const id = auth.userNumber;
console.log('fdhsafidhsafkdjsafhdusafhdsafidgsafdusa', id);
if (!socket) {
const newSocket = io('http://localhost:5000', {
query: {
id: id,
},
});
newSocket.on('disconnect', () => {
setSocket(null);
setTimeout(setupSocket, 3000);
});
newSocket.on('receive-message', (message) => {
console.log('socket.io-client message', message);
receiveMessage(message);
});
}
// return () => newSocket.close();
};
useEffect(async () => {
await setupSocket(); <=== Problem is here
}, []);
return (
<div>
<Sidebar />
</div>
);
};
Messenger.propTypes = {
auth: PropTypes.object.isRequired,
receiveMessage: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => ({
auth: state.auth,
});
export default connect(mapStateToProps, { receiveMessage })(Messenger);```