lost9123193 lost9123193 - 1 year ago 263
React JSX Question

Detecting a refresh event in react

I'm currently using react redux with a wizard form. I've now run into the issue where I need to persist the data in the form or just refresh the data but let the user know.

Currently everything is stored in multiple redux states.

Is there a way to detect a "refresh" event by a user?I will most likely use local storage, but I'm curious of the first option and wondering if it's possible.

Answer Source

If you want to detect a refresh event, It has nothing to do with React, instead use plain Javascript event handler called window.onbeforeunload

window.onbeforeunload = (e) => {
// I'm about to refresh! do something...

However I don't think it's the proper approach to store Redux store, instead you can do something like:

// load state from localStorage
const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
     if (serializedState === null) {
       return undefined; // reducer will return Redux state, as localstorage is null.
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;

const saveToLocalStorage = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
  } catch (err) {
    // ignore error

store.subscribe(() => {
  saveToLocalStorage(store.getState()); // save current state to localstorage.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download