简体   繁体   中英

Render resolved or rejected value of Promise in ReactJS

So, I've got this function fetchData() that returns a promise which is either rejected or resolved. If promise resolves how can i render it on the page?

function Fetchdata() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() > 0.5) {
                resolve(`resolved`);
            } else {
                reject(new Error("err"));
            }
        }, time);
    });
}
  • Provide some initial state for each request state
  • Use promise-chain or async/wait with try/catch
  • Update the render function

Use the power of the promise chain.

class App extends React.Component {
   state = {
     data: null,
     error: null,
     loading: true;
   };

   componentDidMount() {
      fetchData()
        .then(data => {
          // promise resolved
          // handle happy path, update state.data
        })
        .catch(err => {
          // promise rejected
          // handle sad path, update state.error
        })
        .finally(() => {
          // promise is settled
          // set loading false
        });
   }
     
   render() {
      const { data, error, loading } = this.state;

      if (loading) {
        <div>Loading...<.div>;
      }

      return (
          <div>
              <h1></h1>
              {error && <div>Error</div>}
              {data && <div>{data}</div>
          </div>
      );
  }
}

Use async/await in a try/catch/finally in a similar manner

async componentDidMount() {
  try {
    const data = await fetchData();
    // promise resolved
    // handle happy path, update state.data
  } catch(err) {
    // promise rejected
    // handle sad path, update state.error
  } finally {
    // promise is settled
    // set loading false
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM