We’re here to work with you at all stages.

View all services
Build products using the latest engineering practices and designs that aren’t just functional but beautiful with Launch.
Learn more
Rethink how your product delivery teams build and design your products. Architect to build the building blocks that allow experimentation with Amplify.
Learn more
Gain market share by designing and building product features. Gain velocity by embedding our experts in your team with Catalyse.
Learn more
Take control of your cloud costs and technical debt, and add coverage for DevOps with Control.
Learn more

Articles

From user research, digital strategy to solving bold engineering problems. Our team specialises in providing a suite of services that can take an idea from a rough sketch to a secure and fault tolerant digital product.
View all articles

Tutorials

Learning new technologies and frameworks ensures we are ahead of the curve. Here is a collection of step by step tutorials about things we've learnt. Learn with us!
View all tutorials

Culture

We believe the best digital products are built by a diverse and skilled team. We’ve created a safe inclusive workspace, and we believe in diversity. We are a group that believes in software development and design is a craft. This is what unites us.
Learn more

Mission, Vision & Purpose

Our team is diverse. Each coming from a different background and beliefs. We think of product development & design as a craft. We love to learn new ways of improving our craft - be it learning new frameworks, or adding new specialties.
Learn more
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.

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.

Wednesday is a boutique consultancy based in India & Singapore.

Let’s talk

2023