redux rtk查询显示当互联网是关闭的?

nue99wik  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(162)

我使用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']
    }),
njthzxwz

njthzxwz1#

你可以使用navigator.onLine来检查用户的设备当前是否在线,然后监听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 />
    )
  }
}

相关问题