View all tutorials
React to the React App : How To Hard Reload Your React Web App Using Error Boundary
January 7, 2022
Saksham Khatod
Software Engineer
Contents

Good software development practices reduce the possibility of errors. But these pesky creatures still find their way into production. When a user runs into an error the webpage could crash and s/he would have to manually reload it. This leads to a bad user experience. A reload button in case of an error could help the user and nudge them into recovery. More specifically a “Hard reload button” i.e. a button that fetches the webpage from the server instead of the cache.

The error boundary of your web application is a good place to keep the reload button. In most React applications this is a component. It contains a fallback UI, with some text to nudge the user to reload.

Note: This tutorial assumes that you know React and have a good working knowledge of JavaScript.
 
Note: This tutorial assumes that you know React and have good 
working knowledge of javascript.

In this tutorial, you will learn to:

  • Build a basic Error Boundary component
  • Create a button that will hard reload a webpage

Starter Project

We’re going to use the Wednesday react template as a starter project. This is a project we use as a base across all the react projects at Wednesday.

Open the terminal and clone the repository.

 
git clone git@github.com:wednesday-solutions/react-template.git

Navigate to the project on the terminal and run.

 
yarn install

Once done run

 
yarn start

This will start the react template. You should see the following on your browser.

Starter project running in the browser.

Great going so far. You’re now ready to start making changes.

The Error Boundary

The Starter Project comes with a basic error boundary but we will begin by creating an all-new Error Boundary with a refresh button & a start fresh button.

Open the project in your text editor of choice.

Step 1

Navigate to the app/components/ErrorBoundary folder and replace the contents of the index.js file with the following.

 
/**
 *
 * ErrorBoundary
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import errorBoundaryImage from '@images/icon-512x512.png';
import { fonts, styles, media } from '@themes';

// Styled components to make it look nice
const ErrorBoundaryContainer = styled.div`
  text-align: center;
`;

const ErrorBoundaryImage = styled.img`
  margin-top: 8rem;
  width: 25%;
`;

const Heading = styled.h1`
  ${fonts.size.extraLarge()}
  ${fonts.weights.bold()}
  margin-top: 1.375rem;
  font-family: 'Poppins';
  color: #00244f;
`;

const Text = styled.p`
  ${fonts.size.large()}
  ${fonts.weights.normal()}
  color: #00244f;
  margin: 0 26.9% 0 26.9%;

  b {
    ${fonts.weights.bold()}
  }
`;

const StyledButton = styled.button`
  padding: 0.5rem 1.5rem;
  ${styles.borderRadius(4)};
  border: none;
  color: #ffffff;
  background: #af0974;
  margin: 1.5rem 1.5rem 11rem 0;
  cursor: pointer;
`;

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
		// state to hold the error
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.error(error, errorInfo);
  }

  handleRefreshClick() {}

  render() {
    if (this.state.hasError) {
      return (
        
          
          Please bear with us..
          
            Sorry for the inconvenience. We suggest you refresh the page to resolve the issue.
          
          Hit Refresh
        
      );
    }
    return this.props.children;
  }
}
ErrorBoundary.propTypes = {
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node])
};

export default ErrorBoundary;
```

It’s a lot to digest. I’ve left a few comments in the code to make it easy to understand. In a nutshell, this component shows  a button and some text when the error state is set.

Step 2

To test your new component you're going to deliberately trigger an error in the App Container. Open the app/containers/App/index.js file and replace the current App component with the one below.

 
...

export function App({ location }) {
	return new Error();
}
...

Your browser should now show the following.

Application running in the browser showing the refresh button.

Next Steps: The Hard Reload Button

You now have all the building blocks in place. You have a component that will show up when an error occurs. You just need to write the logic to hard reload the page when the user hits the refresh button.

Step 1: Uninstall service workers

Paste in the below code in the handleRefreshClick function in app/components/ErrorBoundary/index.js

 
handleRefreshClick () {
  navigator.serviceWorker.getRegistrations().then((registrations) => {
	  registrations.forEach((registration) => {
		  registration.unregister();
	  });
  });
}

The above piece of code gets all the service workers currently installed for your web app and uninstalls them.

 
Note: We could also use the window.location.reload() function. 
However it would not bypass the service worker and requests will still 
be fetched from the cache.
Step 2: Clear the cache

Then add the following code to the end of the handleRefreshClick() function.

 
async handleRefreshClick() {
		...
    caches.keys().then((keyList) => {
      return Promise.all(
        keyList.map((key) => {
          return caches.delete(key);
        })
      );
    });
  }

The above piece of code removes all browser cache entries.

Step 3: Reload the window

Finally, copy the following snippet and paste it at the end of the same function and add the async keyword before the function name.

 
async handleRefreshClick() {
		...
		setTimeout(() => {
      window.location.reload();
    }, 1000);
  }

This triggers the browser to reload the page. If you reload the webpage in your browser, it should now work as expected. Clicking the 'Hit Refresh' button will hard reload the page.

Yay! You’ve now created a button that can hard reload a webpage.

Craving more after this read? LeadReads is where top C Execs turn for more exclusive insights and stories about digital products. Don’t be left out!

Join
here.

Where to go from here

You’re now able to hard reload webpages using JavaScript and implement it on your website.

The Error Boundary we created here is very basic to keep the focus on the JavaScript bit.  When you do implement it in your website, remember to get as creative as possible i.e. design a much more helpful webpage, add animations, transitions. Have fun with it.

I hope you enjoyed this tutorial as much as I enjoyed writing it. If you think this is helpful please share and leave comments. Alternatively, you can tweet your comments at us here.