I've got a useEffect hook that I use in my App.js file. It puts data into redux store that I need to use in my App. But it renders before the useEffect runs, therefore the data is undefined. The useEffect then runs correctly. I need useEffect to run before anything gets rendered. How could I do that? Or what other solution should I use? I have tried removing the useEffect completely and just running the action, but that results in it running endlessly. This is my code:
function App() {
const app = useSelector(state => state.app);
const auth = useSelector(state => state.auth);
const dispatch = useDispatch();
useEffect(() => {
dispatch(authActions.checkUser());
}, [dispatch]);
console.log(auth.user); //undefined
return (
<ThemeProvider theme={!app.theme ? darkTheme : theme}>
<CssBaseline />
<React.Fragment>
{/* TODO: Display drawer only when logged in */}
{/* <Drawer></Drawer> */}
<Switch>
<Route exact path="/" component={Login} />
<Route exact path="/dashboard">
<Dashboard user={auth.user} /> //auth.user is undefined when this gets rendered
</Route>
<Route exact path="/register" component={Register} />
</Switch>
</React.Fragment>
</ThemeProvider>
);
}
export const checkUser = () => async dispatch => {
let token = localStorage.getItem("auth-token");
if (token === null) {
localStorage.setItem("auth-token", "");
token = "";
}
const tokenRes = await Axios.post("http://localhost:5000/users/tokenIsValid", null, {
headers: { "x-auth-token": token }
});
if (tokenRes.data) {
const userRes = await Axios.get("http://localhost:5000/users/", {
headers: { "x-auth-token": token }
});
dispatch({
type: CHECK_USER,
token,
user: userRes.data
});
}
};