@Lelya666

Почему сообщения socket.io выводятся только в одной вкладке?

Чат с react-redux, redux-thunk, socket.io. Сообщения приходят в консоль с обеих вкладок, но не выводятся друг у друга. Помогите, пожалуйста, разобраться что я написала не правильно.

server
const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)

const port = 3001

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html')
})

io.on('connection', client => {
    let addedUser = false
    
    client.on('new user', username => {
        if (addedUser) return

        client.username = username
        addedUser = true
        console.log(`${client.username} joined`)
        client.broadcast.emit('user join', { username: client.username })
    })
    // message
    client.on('new message', data => {
        console.log('MSG: ', data)
        io.emit('new message', { message: data })
    })

    client.on('disconnect', () => {
        console.log(`${client.username} has disconnected`)
    })
})

http.listen(port, () => {
    console.log(`listening on *:${port}`)
})


api/socket.io
import io from 'socket.io-client'


const socket = io('http://localhost:3001')

export const messagesAPI = {
    addNewMessage(newMessageText) {
        socket.emit('new message', newMessageText)

    },
socketMessage(data) {
    socket.on('new message', data)
},
    newUserSocket(name) {
        socket.emit('new user', name)
    }

}



export default socket;


reducer, экшены и redux-thunk

import { messagesAPI} from "../api";

const SEND_MESSAGE = "SEND_MESSAGE";
const USERS = "USERS"

let initialState = {
    messages: [],
    users: []

}

const messagesReducer = (state = initialState, action) => {
    switch (action.type) {
        case SEND_MESSAGE: {
            let newMessage = action.newMessageText;
            return {
                ...state,
                messages: [...state.messages, {id: 2, message: newMessage}],
            }
        }
        case USERS: {
            let newUser = action.newUserJoined;
            return {
                ...state,
                users: [...state.users,{id: 1, name: newUser }]
            }
        }
        default:
            return state;
    }

}
export const setMessage = (newMessageText) => ({type: SEND_MESSAGE, newMessageText})
export const newUser = (newUserJoined) => ({type: USERS, newUserJoined})

export const messageTC = ( newMessageText) => (dispatch) => {
    messagesAPI.addNewMessage(newMessageText)
    dispatch(setMessage(newMessageText))
}

export  const newUserSocket = (newUserJoined, name) => (dispatch) => {
    messagesAPI.newUserSocket(name)
    dispatch(newUser(newUserJoined))
}

export const socketAdd = (data, newMessageText) => (dispatch) => {
    messagesAPI.socketMessage(data, newMessageText)
    dispatch(setMessage(newMessageText))
}


export default messagesReducer;


контейнер
import React from 'react'
import {connect} from "react-redux";
import Dialogs from "./Dialogs";
import {compose} from "redux";

import {messageTC, socketAdd, newUserSocket} from "../../Redux/reducers/messages-reducer";

class DialogsContainer extends React.Component {

    componentDidMount = () => {
        this.props.userNew(this.props.name)
        this.props.socketAdd(this.props.data)
    }
    addNewMessage = (newMessageText) => {
        this.props.messageTC(newMessageText)

    }
    render() {

        return (
            <Dialogs messages={this.props.messages}
                     addNewMessage={this.props.messageTC}/>
        )
    }
}
let mapStateToProps = (state) => {
    return {
        messages: state.dialogsPage.messages,
        newMessageText: state.dialogsPage.newMessageText,
        messageTC: state.dialogsPage.messageTC
    }
}

export default compose(connect(mapStateToProps, {messageTC, userNew: newUserSocket, socketAdd}))(DialogsContainer)

5dc8408f6d49a018078577.jpeg5dc8409cc3d67013077007.jpeg
  • Вопрос задан
  • 53 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы