Search code examples
javascriptreactjstypescriptreact-nativees6-promise

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);
    });
}

Solution

    • 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
      }
    }