react-scoped-model-swr
v3.0.1
Published
SWR + react-scoped-model
Downloads
13
Maintainers
Readme
react-scoped-model-swr
Usage
Basic Usage
The package exports two model factories: createSWRModel
and createSWRInfiniteModel
.
import { createSWRModel } from 'react-scoped-model';
The simplest form of an SWR Model can be created using just a key value.
const TopItems = createSWRModel('/api/items/top');
which can be mounted like a scoped model instance:
<TopItems.Provider>
<TopItemsList />
</TopItems.Provider>
And can be used with hooks:
import { useSelector } from 'react-scoped-model';
// ...
const data = useSelector(TopItems, (state) => state.data);
All SWR and SWR Infinite models are also subject to the <SWRConfig>
setup.
The second parameter for createSWRModel
is reserved for custom fetching, but it is required to be returned by a higher-order function:
const TopItems = createSWRModel('/api/items/top', () => getTopItems);
The third parameter is an optional parameter and is for the SWR Config.
const TopItems = createSWRModel('/api/items/top', () => getTopItems, {
initialData: [],
});
The fourth parameter is an optional parameter reserved for the scoped model options e.g. displayName
.
Props and Dependent Fetching
SWR and SWR Infinite models can also receive props, and can be used to produce dynamic key, fetcher and config, which can cause dependent or conditional fetching;
const UserDetails = createSWRModel(
({ userId }) => `/api/user/${userId}`,
({ userId }) => () => getUser(userId),
);
// ...
<UserDetails.Provider userId={userId}>
<UserProfile />
</UserDetails.Provider>
You may also use hooks inside these functions as they behave as hooks:
const RecentActivity = createSWRModel(
() => {
// Get the current sign-in token
const token = useAuthToken();
// Only fetch if a token exists,
// signifying the signed-in user's presence
if (token) {
return ['/api/recent-activity', token];
}
return null,
},
() => getRecentActivity,
);
License
MIT © lxsmnsyc