Type safety with dependent fetching #1247
Replies: 6 comments
-
Maybe it could work like this? let { data: user } = useSWR('/api/user')
let { data: projects } = useSWR(t => t`/api/projects?user=${user?.id}`) |
Beta Was this translation helpful? Give feedback.
-
It’s an interesting idea to use template tag for this! While this throw-catch trick for dependent fetching is considered a tiny optimization, to avoid manual checks. However we do see it also brings more problems. One is TS, and the more important thing is readability and maintainability. I’d say we should always recommend explicitly throwing error / returning null, and note about the TS issue in the docs. What do you think? |
Beta Was this translation helpful? Give feedback.
-
Personally I'd rather see the error trick go away, but I'd also like a convenient API. So I'm probably gonna stick with the template string either way. I think the docs might be better off advising people to return null all the time. |
Beta Was this translation helpful? Give feedback.
-
I personally like this idea a lot, specially this API let { data: projects } = useSWR(t => t`/api/projects?user=${user?.id}`) |
Beta Was this translation helpful? Give feedback.
-
It would be handy, we use the same trick with template tag in our codebase |
Beta Was this translation helpful? Give feedback.
-
We recently started integrating SWR into our projects and hit this same issue with Typescript. We have gone with this approach, would this be a valid approach?
The docs say Typescript ready, but some examples of using the framework with Typescript would help make that more truthy. Would be more than happy to help write them if you think there is a need. |
Beta Was this translation helpful? Give feedback.
-
Right now SWR depends on throwing errors in order to do dependent fetching:
However, tools like TypeScript are specifically designed so you never write code like this, making it really awkward to force your type checker to allow an error to be thrown:
In order to get around this, I've written a template tag which allows you to safely construct strings with nullable values:
safestring
will only return a string if every interpolated value is notnull
orundefined
, otherwise it will returnnull
which makes it work with no additional changes touseSWR
.Today's API in SWR is awkward even if you aren't using a type checker though. There are times when JavaScript isn't going to throw an error when you would expect it to. For example:
These manual checks really undo any benefits of having this implicit-error-based API.
Here is an implementation of
safestring
:I don't mind having this outside of SWR, but I just want to offer this up as a potential improvement to the API.
Beta Was this translation helpful? Give feedback.
All reactions