Losing props state data when reloading the page

62 Views Asked by At

Here is the code:

const mapStateToProps = (state, ownProps) => {
  const id = ownProps.match.params.id;
  const sheets = state.firestore.data.sheets;
  const sheet = sheets && sheets[id];
  const rows = sheet.rows;

  return {
    rows: rows,
  };
};

export default compose(
  firestoreConnect(() => ["sheets"]),
  connect(mapStateToProps)
)(Table); 

data structure:

sheets:[
  filename:'abc.txt',
  rows:[ {somedata} , {somedata} ]
]

On loading the page I'm able to load rows, but on reloading I lose the data in state. Here is the error:

TypeError: Cannot read property 'rows' of undefined

errorpage

2

There are 2 best solutions below

0
On

If you think that using redux-persist is overkill for your project, one way could be the following. In your reducer, you could set the initial state in a way that it looks on the local storage for a specific piece of data.

const INIT_STATE = { pieceOfData: JSON.parse(localStorage.getItem("pieceOfData")) }

The first time that piece of data is fetched it will be null. In your reducer than you would have your normal state updates.

case SET_DATA: { return {...state, pieceOfData: action.payload } }

In your action dispatcher, when you fetch the data write it in the LS and dispatch the corresponding action to update the redux store:

localStorage.setItem("pieceOfData", JSON.stringify(pieceOfData));
dispatch({type: SET_DATA, payload: pieceOfData});

Whenever you will need to access that data from the redux store:

const TestComponent = () => {
    const {pieceOfData} = useSelector((state) => state);
    
    return (
        {/*  Remember to check if pieceOfData is already available  */}
        pieceOfData
        ? <p> { pieceOfData.field } </p>
        : <Loader />
    )
}

I wouldn't suggest this approach for big projects; in that case, please take a look at plugins such as redux-persist.

0
On

Since you are using redux, there is a package to help you persist your data in local storage it is called redux-persist. You will have your state even if refreshing/closing the page