mapStateToProps run before useEffect and how to solve?

433 views Asked by At

I have question about mapStateToProps.

I created App.js and dispatch action loadUser inside useEffect to load user every time page refreshed.

const App = () => {
  useEffect(() => {
    store.dispatch(loadUser()); 
  }, []);
  return (
    <Fragment>
      <Navbar />
    </Fragment>
  )
}

Problem is that mapStateToProps inside Navbar is always rendered which cause error before dispatch loadUser called.

Navbar.js

const Navbar = (prop) =>  {
  const user = prop.user; //always return undefined and cause page break
   return (
    <div>{user.name}</div>
   )
}
const mapStateToProps= state => ({
  user:state.loginReducer.user
});

export default connect(mapStateToProps, {})(Navbar);

Can you tell me how to solve this? Thank you so much.

0

There are 0 answers