socketReducer.js 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import {createSlice } from '@reduxjs/toolkit';
  2. import {io} from 'socket.io-client';
  3. import { store } from '../store';
  4. import { removeToken } from './userDataReducer';
  5. const initialState = {
  6. socketStatus: 'idle',
  7. socket: null,
  8. socketUserData: {},
  9. usersOnline: [],
  10. startMessages: [],
  11. allUsers: []
  12. }
  13. const SOCKET_URL = process.env.REACT_APP_SERVER_URL || 'http://localhost:5000';
  14. const connectToSocket = (event) => {
  15. try {
  16. const token = localStorage.getItem('token');
  17. if(token){
  18. const socket = io.connect(
  19. SOCKET_URL,
  20. {auth: {token}})
  21. socket.on('connected', data => {
  22. store.dispatch(getUser(data));
  23. })
  24. .on(event, (data) => {
  25. switch (event){
  26. case 'allmessages':
  27. store.dispatch(getAllMessages(data));
  28. break;
  29. case 'allDbUsers':
  30. store.dispatch(getAllUsers(data));
  31. break;
  32. default:
  33. break;
  34. }
  35. })
  36. .on('newmessage', (data) => {
  37. store.dispatch(addNewMessage(data))
  38. })
  39. .on('ban', (data) => {
  40. store.dispatch(removeToken());
  41. localStorage.removeItem('token');
  42. })
  43. .on('usersOnline', (data) => {
  44. store.dispatch(getUsersOnline(data))
  45. })
  46. .on('disconnect', (data) => {
  47. if( data === 'io server disconnect') {
  48. socket.disconnect();
  49. store.dispatch(removeToken());
  50. }
  51. })
  52. .on('error', e => {console.log('On connected', e)});
  53. return socket;
  54. }
  55. } catch (error) {
  56. console.log('error connecting to socket ', error)
  57. }
  58. };
  59. export const getUserSocketSlice = createSlice({
  60. name: 'userSocket',
  61. initialState,
  62. reducers: {
  63. removeSocket: state => {
  64. state.socket = null
  65. state.socketStatus = 'disconnected'},
  66. getSocket: (state, action) => {
  67. state.socket = connectToSocket(action.payload);
  68. state.socketStatus = 'connected';
  69. },
  70. getUser: (state, action) => {state.socketUserData = action.payload},
  71. getAllMessages: (state, action) => {state.startMessages = action.payload},
  72. getUsersOnline: (state, action) => {state.usersOnline = action.payload},
  73. getAllUsers: (state, action) => {state.allUsers = action.payload},
  74. addNewMessage: (state, action) => {state.startMessages.push(action.payload)}
  75. }
  76. }
  77. );
  78. const {actions, reducer} = getUserSocketSlice;
  79. const getUserSocketReducer = reducer;
  80. export default getUserSocketReducer;
  81. export const {
  82. removeSocket,
  83. getSocket,
  84. getUser,
  85. getAllMessages,
  86. getUsersOnline,
  87. addNewMessage,
  88. getAllUsers
  89. } = actions;