-
Notifications
You must be signed in to change notification settings - Fork 84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error and loading state guide #2
Labels
documents
some further documents
Comments
Sample: check the demo here: https://codesandbox.io/s/q94yj41m1j const mockRequest = (function() {
let counter = 0;
return function() {
counter++;
return new Promise((resolve, reject) => {
setTimeout(() => {
if (counter > 2 && counter < 10) {
reject(new Error("mockError"));
}
resolve("We're cool");
}, 800);
});
};
})();
function App() {
const [isLoading, setLoading] = useState(false);
const [err, setError] = useState(null);
const [clickCallback, status] = useEventCallback(
(event$, state$) =>
event$.pipe(
tap(() => {
setLoading(true);
setError(null);
}),
switchMap(event => {
return from(mockRequest()).pipe(
catchError(error => {
setError(error);
return of("got error");
})
);
}),
tap(() => setLoading(false))
),
"nothing"
);
return (
<div className="App">
<p>
{isLoading ? "is loading!...." : `${status}`}
{err && ` - ${err.toString()}`}
</p>
<button onClick={clickCallback}>send request</button>
</div>
);
} |
@zry656565 More clear example, without dirty const mockRequest = (function() {
let counter = 0;
return function() {
counter++;
return new Promise((resolve, reject) => {
setTimeout(() => {
if (counter > 2 && counter < 10) {
reject(new Error("mockError"));
}
resolve("We're cool");
}, 800);
});
};
})();
function App() {
const [clickCallback, [status, result]] = useEventCallback(
(event$, state$) =>
event$.pipe(
switchMap(event => {
return from(mockRequest()).pipe(
map(result => ["success", result]),
catchError(error => {
return of(['error', error]);
}),
startWith(["loading", null])
);
})
),
["nothing", null]
);
const isSuccess = status === "success";
const isError = status === "error";
return (
<div className="App">
<p>
{isSuccess ? result : status}
{isError && ` - ${result.toString()}`}
</p>
<button onClick={clickCallback}>send request</button>
</div>
);
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expose API like:
The text was updated successfully, but these errors were encountered: