I am trying to fire a toast when react-query
returns data, currently the toast is displayed with no data. How can I show the toast when data has loaded?
component:
function useAppNeedsAnUpdate() {
const versionControl = useVersionControlQuery();
useEffect(() => {
const showUpdateToast = () => {
Toast.show({
text1: versionControl.data?.header,
text2: versionControl.data?.body,
type: 'appUpdate',
autoHide: false,
props: {
link: versionControl.data?.storeLink,
},
});
};
showUpdateToast();
}, [versionControl.isSuccess]);
}
export default useAppNeedsAnUpdate;
query:
export function useVersionControlQuery() {
return useQuery({
queryKey: [QUERY_KEYS.RESULT, normalisedAppVersion],
queryFn: getVersionControl,
staleTime: STALE.DAYS.ONE,
});
}
To Make sure the toast is displayed only when the React-Query has successfully returned data you have to conditionally trigger the toast based on isSuccess
status make sure data exists. Currently showUpdateToast
is called every time the useEffect
runs.
function useAppNeedsAnUpdate() {
const versionControl = useVersionControlQuery();
useEffect(() => {
if (versionControl.isSuccess && versionControl.data) {
Toast.show({
text1: versionControl.data.header,
text2: versionControl.data.body,
type: 'appUpdate',
autoHide: false,
props: {
link: versionControl.data.storeLink,
},
});
}
}, [versionControl.isSuccess, versionControl.data]);
}
export default useAppNeedsAnUpdate;
You can also use other flags to optimize the code:
isLoading
: Indicates that the query is in the process of fetching data.isError
: Indicates that the query encountered an error while fetching.isFetching
: Indicates that the query is actively fetching data (can be true even after isSuccess if the data is being refreshed).isStale
: Indicates whether the data is stale according to the configured staleTime.isIdle
: Indicates that the query has not started fetching yet (usually when enabled is set to false).