managing ui states #440
Replies: 2 comments 3 replies
-
Thank you for bringing up this great topic! Personally, I think the lib itself should only expose a minimal amount of atomic values (data, error, isRevalidating, ...) and let the user to derive the actual states (like what you are doing with Here're the reasons that I think the SWR lib itself should not give you the states directly: First, there're too many possible states and not all the states are always needed by the user. If you have N atomic values and each one has 2 states, you get 2^N possible combinations in total. For example when using pagination or infinite loading, you will have Also SWR has no knowledge about the UI or API data shape. It only does the fetch and returns the data. That means, it can possible be wrong if it tries to cover things that are out of its scope. Say I have a
In that case, the error value doesn't always mean an error. It's the best to let the user to decide what's the state and which UI to use for that state. We have tons of customized SWR hooks, many of them have different states (especially with pagination cases): function useUser() {
const { data, error } = useSWR('/api/user')
const isLoggedOut = !data && error?.status === 404
return {
data,
error: isLoggedOut ? null : error,
isLoggedOut
}
}
function useProjects() {
const { data, error } = useSWR('/api/projects')
return {
data,
error,
isEmpty: data && data.length === 0
}
} The last reason I can think of is Suspense. With Suspense, <ErrorBoundary fallback={<h2>Could not fetch posts.</h2>}>
<Suspense fallback={<h1>Loading posts...</h1>}>
<ProfileTimeline />
</Suspense>
</ErrorBoundary> That way it's impossible for SWR to manage the UI state. It still (and can only) does the job of returning 3 atomic values (data, error, loading). |
Beta Was this translation helpful? Give feedback.
-
I usually use Suspense to handle the loading state and Error Boundaries to handle the error states, this way my component only need to care about the state where I have |
Beta Was this translation helpful? Give feedback.
-
Curious how swr handles ui state management. For instance, it is hard sometimes to determine based on the state of the objects which state the UI is in (data === undefined, error !== undefined, isRevalidating, etc)...
react-query
uses a (somewhat confusing?) combination of a query result type and some booleans (isStale etc.). In swrv, I'm using a user-land hook to determine states: https://github.com/Kong/swrv#useswrvstate but wanted to see what others were doing.Beta Was this translation helpful? Give feedback.
All reactions