DEV Community

Cover image for React to the React App: How to hard reload your React Web App?
Wednesday Solutions
Wednesday Solutions

Posted on

React to the React App: How to hard reload your React Web App?

Good software development practices reduce the possibility of errors. But these pesky creatures still find their way in 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 good 
working knowledge of javascript.
Enter fullscreen mode Exit fullscreen mode

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](mailto:git@github.com):wednesday-solutions/react-template.git
Enter fullscreen mode Exit fullscreen mode

Navigate to the project on the terminal and run.

npm install
Enter fullscreen mode Exit fullscreen mode

Once done run

npm start
Enter fullscreen mode Exit fullscreen mode

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

Image description

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 (
        <ErrorBoundaryContainer>
          <ErrorBoundaryImage src={errorBoundaryImage} />
          <Heading>Please bear with us..</Heading>
          <Text>
            Sorry for the inconvenience. We suggest you <b>refresh the page</b> to resolve the issue.
          </Text>
          <StyledButton onClick={this.handleRefreshClick}>Hit Refresh</StyledButton>
        </ErrorBoundaryContainer>
      );
    }
    return this.props.children;
  }
}
ErrorBoundary.propTypes = {
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node])
};

export default ErrorBoundary;
Enter fullscreen mode Exit fullscreen mode

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 the 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();
}
...
Enter fullscreen mode Exit fullscreen mode

Your browser should now show the following.

Image description

Hard Reload

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();
      });
  });
}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Step 2: Clear the cache

The 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);
        })
      );
    });
  }
Enter fullscreen mode Exit fullscreen mode

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);
  }
Enter fullscreen mode Exit fullscreen mode

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 this piqued your interest, check out other articles by Wednesday Solutions and tweet your comments at us.

By: Saksham Khatod
Originally appeared on https://www.wednesday.is/writing-tutorials/react-to-the-react-app-how-to-hard-reload-your-react-web-app-using-error-boundary

Top comments (1)

Collapse
 
ayeshabaloch123 profile image
Ayesha Ali

More power to you man🙌