'Ensure redux state is current across browser sessions

What is the best practice for refreshing state across browser sessions without a third party library? I need to make sure data is current before triggering a download on an object in state. I have tried using multiple useEffect's (one to update the data, one to trigger the download) but the state function calls the download on the state in props before updating the object. I know state is set asynchronously but haven't been able to resolve this issue.

function DownloadButton(props){
  const {selected} = props;
  let selectedFile = selected ? props.all.files[selected] : null;
  const [downloaded, setDownloaded] = useState(false);

  useEffect(() => {
    if(selected && downloaded === true){
      selectedFile.download();
    }
      setDownloaded(false);   
  }, [props.all, downloaded]);

  return(
     <DownloadButton 
        onClick={() => {
          //trigger refresh of props.all
          props.refresh();
          //below works if wrapped in setTimeout
          setDownloaded(true);
        }}
     />
  );

}

const mapStateToProps = state => {
  return {
    all: state.all
  }
}

const mapDispatchToProps = dispatch => {
  return {
    refresh: () => dispatch({type: "GET_ALL"})
  } 
}

export default connect(mapStateToProps, mapDispatchToProps)(DownloadButton);



Solution 1:[1]

It seems to me that the component is a bit too involved with the refresh mechanism, so I'd delegate that to a redux action instead:

// async download action
const downloadFile = (fileName) => async (dispatch, getState) => {
  await dispatch(refresh());
  const file = getState().all.files[fileName];
  file.download(); // it's not recommended to have functions in redux state btw
};

function DownloadButton(props) {
  const { selected, downloadFile } = props;

  return(
    <>
      {!!selected && <DownloadButton onClick={() => downloadFile(selected)} />}
    </>
  );
}

const mapDispatchToProps = { downloadFile };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 timotgl