Answer the question
In order to leave comments, you need to log in
How to make useEffect run before component is mounted?
There is a component that pulls data from localStorage in the effect, but after mounting the component redirects to the authorization page, although there is authorization data in localStorage. Question: how to make it mounted after the effect, or do some check before showing the routes?
const App = (props) => {
useEffect(() => {
props.checkIsAuthUser();
}, []);
useEffect(() => {
setTheme("light");
}, []);
return (
<ApolloProvider client={client}>
<Router>
<Switch>
<Route
path={"/auth"}
render={(routeProps) => <AuthPage {...routeProps} />}
/>
{props.isAuth?
<>
<Route
path={"/app"}
render={(routeProps) => <Application {...routeProps} />}
/>
<Route exact path={"/"}>
<Redirect to={"/app/today"} />
</Route>
<Route
path={"/:err"}
render={(routeProps) => <RedirectPage {...routeProps} />}
/>
</>
:
<Redirect to={"/auth/login"} />
}
</Switch>
</Router>
</ApolloProvider>
);
};
const mapStateToProps = (store) => ({
isAuth: store.auth.login.state,
});
export default compose(
withSuspens,
connect(mapStateToProps, { checkIsAuthUser })
)(App);
Answer the question
In order to leave comments, you need to log in
No way, useEffect is always called after the component is mounted.
Extract the content into a separate component and conditionally render. The only way.
try doing unmount in useEffect
useEffect(() => {
//mount
return () => {
//unmount
}
}, [])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question