V
V
Vann Damm2020-11-23 10:35:42
React
Vann Damm, 2020-11-23 10:35:42

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

2 answer(s)
T
twolegs, 2020-11-23
@twolegs

No way, useEffect is always called after the component is mounted.
Extract the content into a separate component and conditionally render. The only way.

T
tervizator, 2020-11-23
@tervizator

try doing unmount in useEffect
useEffect(() => {
//mount
return () => {
//unmount
}
}, [])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question