Re-rendering Ionic React on a route ( don't want to reload the data )

Viewed 2161

I'm trying to build an app with Ionic React. I have an issue with the router.

App.tsx

<IonRouterOutlet>
         <Route path="/stats" render={() => <Stats/>} exact={true} />
         <Route path="/orders" component={Orders} exact={true} />
         <Route path="/" render={() => <Redirect to="/stats" />} exact={true} /></IonRouterOutlet>  

In my component Stats, I use useEffect to load the data from the API

 useEffect(() => {
   OrdersService.getOrders().then(resultat => {
     setDataOrders(resultat);
    });
     return function cleanup() {
       // Clean the data

     }


  }, []);

If I go to my component Orders and go back to stats, react don't reload the data from the API. Do you have any solution to force the reload ?

Thanks in advance.

1 Answers

Ionic works differently to how you might expect, the routes are rendered even if they have not been entered yet. And when you navigate to a new route, the cleanup function of useEffect does not get called. This is by design so routes are already rendered and good to go when you navigate between pages.

What you want to use is the useIonViewWillEnter hook which will be called when the route is about to be entered.

import React, { useState } from "react";
import { useIonViewWillEnter } from "@ionic/react";

export const DataOrdersView = () => {
  const [dataOrders, setDataOrders] = useState([]);

  useIonViewWillEnter(() => {
    OrdersService.getOrders().then((resultat) => {
      setDataOrders(resultat);
    });
  });

  return <div>Your View</div>;
};

You can read more here, https://ionicframework.com/docs/react/lifecycle

Related