Quantcast
Channel: Active questions tagged react-native+ios - Stack Overflow
Viewing all articles
Browse latest Browse all 16750

React-Native Memory leak, possibly from redux, please see details

$
0
0

So I'm building a react-native application for my work, and I'm using redux and websockets. I'm experienced a bad memory leak when i go to the messenger screen repeatedly, which i suspect has something to do with redux actions / state changes being stored in memory. I have a pretty nested store object that is being modified when chat messages load/ a new message comes in. The leak is especially bad in debug mode, but improves significantly in production but the memory still climbs over time. Could someone take a look at my reducer and tell me if the way im modified nested properties in an array may be causing this and if there is any alternative? I'm also using "store.getState()" and store.dispatch() in the socket because it is not a react component so i have no other means of getting things like the auth token since there are no props.

I'm using a lot of .find() and .map() methods to modify my nested redux state (adding messages to a chat room) and im wondering if these objects are being stored in memory every time i trigger these functions. Any help would be much appreciated!Thank you

Here is my reducer:

const chatReducer = (state = {rooms: [], selectedChat: ''}, action) => {  switch (action.type) {    case 'LOAD_CHATS':      return {...state, rooms: [...state.rooms, ...action.rooms]};    case 'LOAD_MESSAGES':      const newRooms = state.rooms.map(room => {        if (room.id === state.selectedChat) {          room.messages = action.messages;        }        return room;      });      return {...state, rooms: newRooms};    case 'NEW_MESSAGE':      const newMessages = state.rooms.map(room => {        if (room.id === action.item.room) {          return {            ...room,            messages: [              ...room.messages,              {                user: action.item.user,                date: action.item.date,                message: action.item.msg,              },            ],          };        }        return room;      });      return {...state, rooms: newMessages};    case 'SELECTED_CHAT':      return {...state, selectedChat: action.id};    case 'SYNC_MESSAGES':      const roomById = state.rooms.find(room => room.id === action.id);      const syncedMessages = action.msgs.map(msg => {        if (!roomById.messages.find(el => el.id === msg.id)) {          return msg.messages;        }      });      const roomMessages = state.rooms.map(room => {        if (room.id === action.id) {          return {            ...room,            messages: [...room.messages, ...syncedMessages],          };        }        return room;      });      return {...state, rooms: roomMessages};    default:      return state;  }};export default chatReducer;

and here is my socket utilities file:

import io from 'socket.io-client';import {store} from '../redux/store';let socket = null;const getSocket = () => {  return socket;};const init = () => {  const token = store.getState().auth.token;  socket = io.connect('********************',    {      query: {token},      transports: ['websocket'],    },  );};const handleConnect = data => {  socket.on('connecting', () => {    console.log('Socket connecting...');  });  socket.on('connect', x => {    console.log('CONNECTED', x);    socket.emit('RegisterUser', {      User: data.username,      Client: data.client,      System: 'Mobile',    });  });  socket.on('ChatMessages', msgs => {    store.dispatch({type: 'LOAD_MESSAGES', messages: msgs[0].messages});  });  socket.on('UserTypeing', msg => {    store.dispatch({type: 'USER_TYPING', data: msg});  });  socket.on('UserTypeingStopped', msg => {    store.dispatch({type: 'STOPPED_TYPING', user: msg});  });  socket.on('NewMessage', msg => {    store.dispatch({type: 'NEW_MESSAGE', item: msg});  });  socket.on('SortedMessages', msgs => {    const id = store.getState().chat.selectedChat;    store.dispatch({type: 'SYNC_MESSAGES', msgs: msgs.resources, id});  });  socket.on('connect_failed', msg => {    console.log(msg, 'CONNECT FAILED');  });  socket.on('connect_error', msg => {    console.log(msg, 'Connect Error!');  });  socket.on('connect_timeout', msg => {    console.log(msg, 'timeout!');  });  socket.on('error', msg => {    console.log(msg, 'Error!');  });  socket.on('reconnect', attemptNumber => {    console.log('recon attempt:', attemptNumber);  });};const getRooms = () => {  socket.on('GetChatRooms', rooms => {    const arr = [];    rooms.forEach(room => {      if (!store.getState().chat.rooms.find(el => el.id === room.id)) {        arr.push(room);      }    });    if (arr.length) {      store.dispatch({type: 'LOAD_CHATS', rooms: arr});    }  });};const getRoomMessages = id => {  console.log('GETROOMMESSAGES');  socket.emit('GetChatMessages', id);};const userUpdate = () => {  socket.on('userupdate', data => {});};const handleDisconnect = () => {  socket.on('disconnect', () => {    console.log('DISCONNECTED');  });};const startTyping = roomId => {  socket.emit('SendRoomImTyping', {room: roomId});};const stopTyping = roomId => {  socket.emit('SendRoomStopTyping', {room: roomId});};const sendRoomMessage = (roomId, message) => {  socket.emit('SendRoomMessage', {room: roomId, message});};const updateRoomMessages = (id, start) => {  console.log(id, start);  socket.emit('GetChatMessagesFiltered', {id, start});};const disconnect = () => {  socket.disconnect();};const SocketTools = {  init,  handleConnect,  getRooms,  getRoomMessages,  updateRoomMessages,  userUpdate,  disconnect,  handleDisconnect,  getSocket,  sendRoomMessage,  startTyping,  stopTyping,};export default SocketTools;

Viewing all articles
Browse latest Browse all 16750

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>