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.
IonReactRouter uses the popular React Router library under the hood. With Ionic and React Router, you can create multi-page apps with rich page transitions. Everything you know about routing using React Router carries over into Ionic React. Let's take a look at the basics of an Ionic React app and how routing works with it.
The IonPage component wraps each view in an Ionic React app and allows page transitions and stack navigation to work properly. Each view that is navigated to using the router must include an IonPage component. There are several options available when routing to different views in an Ionic React app.
Re-render component when state changes Any time a React component state has changed, React has to run the render () method. class App extends React.Component { componentDidMount() { this.setState({}); } render() { console.log('render () method') return < h1 > Hi!</ h1 >; } } In the example above I’m update the state when the component mounts.
The IonReactRouter component wraps the traditional BrowserRouter component from React Router, and sets the app up for routing. Therefore, use IonReactRouter in place of BrowserRouter. You can pass in any props to IonReactRouter and they will be passed down to the underlying BrowserRouter.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With