RCohen
RCohen

Reputation: 1992

Simple loading before a success message

I'm trying to implement something really simple, where I want to display a loading between messages. A live example here

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      submitSuccess: false
    };
  }

  onClick = () => {
    console.log("click");
    this.setState({
      isLoading: false,
      submitSuccess: true
    });
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.onClick}>click</button>
        {this.state.isLoading ? (
          <p>loading...</p>
        ) : this.state.submitSuccess ? (
          <p>sucess!</p>
        ) : (
          <p>are you sure?</p>
        )}
      </div>
    );
  }
}

What I am trying to do is this example below:

  1. Are you sure?
  2. Loading...
  3. Success!

But I'm not doing this right, since I'm not working properly with the ternary operators. How can I improve this?

Thanks! :)

Upvotes: 2

Views: 285

Answers (1)

Manu
Manu

Reputation: 10934

Fixed here: https://codesandbox.io/s/rln4oz4vwq

Basic idea: Set loading to false by default, because you are not loading anything. On click of button, set loading to true as you truly are. Then on completion of async stuff, set loading to false and submitSuccess to true to indicate you are done.

Code:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      submitSuccess: false
    };
  }

  onClick = () => {
    console.log("click");
    this.setState({
      isLoading: true
    });

    //lets assume you now do some async stuff and after 2 seconds you are done
    setTimeout(() => {
      this.setState({
        isLoading: false,
        submitSuccess: true
      });
    }, 2000);
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.onClick}>click</button>
        {this.state.isLoading ? (
          <p>loading...</p>
        ) : this.state.submitSuccess ? (
          <p>success!</p>
        ) : (
          <p>are you sure?</p>
        )}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 2

Related Questions