React websockets disappear on refresh

Viewed 32

So I have a websocket connection that is open and I notice once I refresh the page the websocket messages disappears. I've read online that this is supposed to happen. What is a good way to persist these messages so that they do not disappear. Right now I have the websocket messages in a react state. I've seen some say localstorage or cookies, but I don't think that is scalable as their can be thousands of messages in minutes that could overload the browser storage? Below I am using react-use-websocket package and I get the last message and store that inside a state array. That is the wrong approach I need a longer storage solution.

const { lastJsonMessage, lastMessage, sendMessage, readyState, getWebSocket } = useWebSocket(resultUrl, {
    //Will attempt to reconnect on all close events, such as server shutting down
    shouldReconnect: () => true,
    reconnectAttempts: 10,
    reconnectInterval: 3000
  });

  useEffect(() => {
    const val = lastJsonMessage ? JSON.parse(lastJsonMessage as unknown as string) : {};
    if (val !== null && Object.keys(val).length > 0) {
      setMessageHistory((prev) => prev.concat(val));
    }
  }, [lastJsonMessage, setMessageHistory]);

  // Get Video assets after finishing;
  useEffect(() => {
    messageHistory.forEach((msg) => {
      const { type } = msg;
      if (type === 'video.live_stream.recording' || type === 'video.live_stream.active') {
        const localPlaybackId = msg.data?.playback_ids[0];
        setPlaybackId(localPlaybackId);
      }
      setVideoType(type);
    });
  }, [messageHistory, videoType]);

  const connectionStatus = {
    [ReadyState.CONNECTING]: 'Connecting',
    [ReadyState.OPEN]: 'Open',
    [ReadyState.CLOSING]: 'Closing',
    [ReadyState.CLOSED]: 'Closed',
    [ReadyState.UNINSTANTIATED]: 'Uninstantiated'
  }[readyState];

  if (liveStreamId) {
    sendMessage(liveStreamId);
  }

  messageHistory.filter((msg) => {
    msg.data.id === liveStreamId;
  }); 
1 Answers

in this case, usually when the app is loaded you should do a GET request to the server in order to load all the last messages. Also since you are talking about "thousands of messages" you should implement a lazy loading aka paginator or infinite-scroll

Related