rtk query show when internet is off?



我使用rtk查询。

如果我关闭我的互联网连接,导航到一个屏幕,我没有看到加载器或其他东西,我什么也没看到。所以当我打开网络连接时,什么也没发生。当网络离线时,我如何告诉用户我向他发送消息,当网络打开时,rtk查询自动重新获取数据?

Cart.tsx

const ShoppingCart: React.FC<Props> = ({}) => {
const user_id = useSelector((state: RootState) => state.Auth.user.user_id);
const { data, isFetching, isLoading } = useCartQuery({user_id});
if(isLoading) {
return (
<Loader />
)
} else if(data && data.length > 0) {
return (
<ShoppingCartComponent
products={data}
/>
)
} else if(data && data.length === 0) {
return (
<ShoppingCartEmpty />
)
}
}
export default ShoppingCart;

车。ts API

reducerPath: 'ShoppingCartApi',
baseQuery: fetchBaseQuery({ baseUrl: `${API_ENDPOINT}/` }),
tagTypes: ['CART'],
endpoints: (builder) => ({
cart: builder.query<IProduct[], { user_id?: number; unlogged_uuid?: string; }>({
query: (data) => ({
url: '/cart',
method: 'POST',
body: data
}),
providesTags: ['CART']
}),

可以使用navigator.onLine检查用户的设备当前是否在线。然后监听在线事件,当设备的互联网连接恢复并重新获取数据时触发。

const ShoppingCart: React.FC<Props> = ({}) => {
const user_id = useSelector((state: RootState) => state.Auth.user.user_id);
const { data, isFetching, isLoading, refetch } = useCartQuery({user_id});
useEffect(() => {
const handleOnlineEvent = () => {
// Refetch data from the API when the online event is fired
refetch();
};
window.addEventListener('online', handleOnlineEvent);
return () => {
window.removeEventListener('online', handleOnlineEvent);
};
}, []);
if (!navigator.onLine) {
return (
<div>
<p>You are currently offline. Please check your internet connection and try again.</p>
</div>
);
}
if (isLoading) {
return (
<Loader />
)
} else if(data && data.length > 0) {
return (
<ShoppingCartComponent
products={data}
/>
)
} else if(data && data.length === 0) {
return (
<ShoppingCartEmpty />
)
}
}

相关内容

  • 没有找到相关文章

最新更新