Skip to content

Commit

Permalink
docs(readme): add alternate sequential flow
Browse files Browse the repository at this point in the history
  • Loading branch information
code-forger committed Feb 23, 2023
1 parent ef9ff1c commit d8849a5
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -354,8 +354,12 @@ const MyFavoriteBook = () => {
const { isLoading: loadingProfile, data: profile } = useFetchye('http://example.com/api/profile');

const profileHasBookId = !loadingProfile && profile?.body?.favoriteBookId;
const { isLoading: loadingBook, data: favoriteBook } = useFetchye(`http://example.com/api/books/${profile?.body?.favoriteBookId}`, {
const { isLoading: loadingBook, data: favoriteBook } = useFetchye('http://example.com/api/books', {
defer: !profileHasBookId,
method: 'POST',
body: JSON.stringify({
bookId: profile?.body?.favoriteBookId,
}),
});

if (loadingProfile) {
Expand All @@ -382,6 +386,44 @@ const MyFavoriteBook = () => {
};
```
Alternatively, you can pass a function as the first parameter to useFetchye, if this function throws an exception the call will automatically be 'deferred' until the function does not throw.
This only works if the sequential data is passed to the second call in the url.
In this example, the function will throw `Cannot read properties of undefined` when trying to access 'favoriteBookId' in the non-existent body of the profile:
```jsx
import React from 'react';
import { useFetchye } from 'fetchye';

const MyFavoriteBook = () => {
const { isLoading: loadingProfile, data: profile } = useFetchye('http://example.com/api/profile');
const { isLoading: loadingBook, data: favoriteBook } = useFetchye(() => `http://example.com/api/books/${profile.body.favoriteBookId}`);

if (loadingProfile) {
return (<p>Loading Profile...</p>);
}
if (profile.status !== 200) {
return (<p>Oops!</p>);
}
if (loadingBook) {
return (<p>Loading Favourite Book...</p>);
}
if (favoriteBook.status !== 200) {
return (<p>Oops!</p>);
}

return (
favoriteBook.status === 200 && (
<>
<h1>My Favorite Book</h1>
<h2>{favoriteBook.body.title}</h2>
</>
)
);
};
```
### Refreshing
```jsx
Expand Down

0 comments on commit d8849a5

Please sign in to comment.