Search code examples
react-nativereduxexporedux-toolkitrtk-query

rtk query show when internet is off?


I use rtk query.

if I close my internet connection and navigate to a screen I see no Loader and or something else I see nothing. So when I turn on my internet connection then nothing happens. How can I say to the user when the internet is offline that I send him a message and when Internet is on that the rtk query automatically refetch the data ?

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;

Cart.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']
    }),

Solution

  • You can use the navigator.onLine to check if the user's device is currently online. Then listen for the online event, which is fired when the device's internet connection is restored and refetch data.

    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 />
        )
      }
    }