How to set initialData
so that typescript casting isn't required
#1301
Replies: 7 comments 11 replies
-
we discussed this a bit here: #1297 or at least it is similar. I think that if the query is |
Beta Was this translation helpful? Give feedback.
-
Thanks for the reply! I tested the case where |
Beta Was this translation helpful? Give feedback.
-
I'm curious if anyone has solved this yet? I'm running into the same issue. Real simple hook const useFetchGeoData = (options = {}): UseQueryResult<Geo[]> => {
return useQuery<Geo[]>("geos", fetchGeos, {
...options,
initialData: [],
});
}; then the consuming components look like const { data: geos } = useFetchGeoData({
notifyOnChangeProps: ["data"],
}); With the I'm aware I could do something like const useFetchGeoData = (options = {}) => {
const query = useQuery<Geo[]>("geos", fetchGeos, options);
return {
...query,
data: query?.data ?? [],
};
}; But the project I'm on also requires a return type, which |
Beta Was this translation helpful? Give feedback.
-
also the same issue occur when you use |
Beta Was this translation helpful? Give feedback.
-
Hey I know that this is an old discussion. However, for those that come here googling like I did, I have a clean solution for this problem. You can add initial data in typescript when unpacking the query like this. const { data: items = [] } = useQuery(QUERIES.items, API.getAllItems); |
Beta Was this translation helpful? Give feedback.
-
Hi from the future, this is the solution I found: {myQuery.isSuccess && <Component name={myQuery.data!.name} />} I think using the |
Beta Was this translation helpful? Give feedback.
-
For me, I'm using this piece of code const query = useQuery({
...options,
initialData,
});
if (!query.data) {
throw 'data should be defined at this point';
}
return query; // query.data is always defined here Don't know if it's good practice 😬 |
Beta Was this translation helpful? Give feedback.
-
This is such an awesome, powerful library and given how expressive
useQuery
is, I'm wondering if there are specific configuration patterns that work better for TypeScript users than my naive parsing of the docs.In particular, is there a "best practice" or common idiom for setting the
initialData
such that casting isn't required?The problem
Here's an example w/ inline comments:
Possible solution
I'm currently solving this with a "cast and comment", essentially codifying my understanding of the useQuery api:
Another possible solution
An alternative is to set an es6 default value on
data
, but that feels wrong. I'd prefer to letuseQuery
be in control ofdata
's value:Beta Was this translation helpful? Give feedback.
All reactions