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