Change button text on loading state in Reactjs

In this tutorial, we will learn how to change button text if there is any loading state in Reactjs.

Update Button Text in Reactjs

For example, let’s say you are making a network call with Rest API, by the time the response is provided, the component will be in the loading state.

At this time we can update the text of the button to show that we are currently in the loading state.

We will have to maintain the state in the component using useState() to track the loading and according what is the state, will change the text of the button.

import {useState} from "react";

export default function App() {
  const [isLoading, setLoading] = useState(false);
  
  return (
    <div className="App">
      <button onClick={() => setLoading(true)}>{isLoading ? "...loading" : "click"}</button>
    </div>
  );
}

In this example, when we click on the button the state is updated and isLoading becomes true which causes the component to re-render and update the button text to ...loading.

Using a mock-server to mimic network call

We can make use of a mock server to show the case that a network call is made and update the loading state accordingly.

import { useState } from "react";

function getRandomBool(n) {
  const threshold = 1000;
  if (n > threshold) n = threshold;
  return Math.floor(Math.random() * threshold) % n === 0;
}

const FAILURE_COUNT = 10;
const LATENCY = 1000;

function mockServer() {
  return new Promise((resolve, reject) => {
    const randomTimeout = Math.random() * LATENCY;
    setTimeout(() => {
      if (getRandomBool(FAILURE_COUNT)) {
        reject();
      } else {
        resolve();
      }
    }, randomTimeout);
  });
}

export default function App() {
  const [isLoading, setLoading] = useState(false);

  const handleClick = async () => {
    try {
      setLoading(true);
      let resp = await mockServer();
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="App">
      <button onClick={handleClick}>
        {isLoading ? "...loading" : "click"}
      </button>
    </div>
  );
}

Here with the click of the button, we invoke the mock server, before making the network call, we update the loading state to true in the try block and once the call is finished we update it to false in the finally block.