DEV Community

SagarTrimukhe
SagarTrimukhe

Posted on

No Internet Connection wrapper for React apps

Imagine,
We have a web application that heavily depends on the backend server for information (eg. records in a table) and that information needs to be constantly updated. We might think to use some polling mechanism.

But if the data received from the server is directly stored in a React state variable and if the user loses the internet connection then there are chances of updating the state with empty data.

So, instead of showing empty data, we can show a message, something like "No internet connection."

How can we do that?

We can write a wrapper component and wrap the entry-level component. So whenever the internet connection is lost, a custom page/message can be shown.

Here I have used the navigator.onLine API to get the network status.

enough story, show me the code :)

Main component

import './App.css';
import NoInternetConnection from './NoInternetConnection'

function App() {
  return (
    <div className="App">
        <NoInternetConnection>
        <h1>My first post on DEV!!</h1>
        </NoInternetConnection>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Wrapper component

import React, {useState, useEffect} from 'react';

const NoInternetConnection = (props) => {
    // state variable holds the state of the internet connection
    const [isOnline, setOnline] = useState(true);

    // On initization set the isOnline state.
    useEffect(()=>{
        setOnline(navigator.onLine)
    },[])

    // event listeners to update the state 
    window.addEventListener('online', () => {
        setOnline(true)
    });

    window.addEventListener('offline', () => {
        setOnline(false)
    });

    // if user is online, return the child component else return a custom component
    if(isOnline){
    return(
        props.children
    )
    } else {
        return(<h1>No Interner Connection. Please try again later.</h1>)
    }
}

export default NoInternetConnection;
Enter fullscreen mode Exit fullscreen mode

Here is the demo.

ezgif.com-gif-maker

That's it. By the way, this is my first post on DEV (damn! on the internet :)). Feedback is appreciated.

Latest comments (2)

Collapse
 
diwanshumidha profile image
Diwanshu Midha

It would be much more useful if we use a hook like useOfflinestatus leaving the user much more flexibility

import React from "react";

export default function useOffline() {
  console.log("Running hook");
  // Set up state
  const [isOffline, setIsOffline] = React.useState(false);

  // Set up handlers
  function onOffline() {
    console.log("Going offline");
    setIsOffline(true);
  }

  function onOnline() {
    console.log("Going online");
    setIsOffline(false);
  }

  // Run this on mount only - due to []
  React.useEffect(() => {
    console.log("Setting handlers...");
    // Change state whenver these occur..
    window.addEventListener("offline", onOffline);
    window.addEventListener("online", onOnline);

    // Return a function removing these handlers on unmount
    return () => {
      console.log("Unmounting");
      window.removeEventListener("offline", onOffline);
      window.removeEventListener("online", onOnline);
    };
  }, []);

  // Return the state value...
  return isOffline;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tmashwani profile image
tmashwani

if props.children is any form or any page when get establish our internet connection we want the previous sate of props.children how will we tackle this.