admin 管理员组文章数量: 1086019
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 pletely 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="/" ponent={Login} />
<Route exact path="/dashboard">
<Dashboard user={auth.user} /> //auth.user is undefined when this gets rendered
</Route>
<Route exact path="/register" ponent={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
});
}
};
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 pletely 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="/" ponent={Login} />
<Route exact path="/dashboard">
<Dashboard user={auth.user} /> //auth.user is undefined when this gets rendered
</Route>
<Route exact path="/register" ponent={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
});
}
};
Share
Improve this question
asked Sep 19, 2020 at 10:56
FilipFilip
9556 gold badges20 silver badges43 bronze badges
0
2 Answers
Reset to default 5I need useEffect to run before anything gets rendered. How could I do that?
You cannot make useEffect
run before the initial render.
Just like ponentDidMount
in class ponents runs after the initial render, useEffect
runs after the initial render and then its execution depends on whether you pass the second argument, i.e. dependency array to useEffect
hook.
what other solution should I use?
You can conditionally render the content by making sure that you render the asynchronously fetched data only after it is available.
return (
{ auth ? <render content> : null}
);
or
return (
{ auth && <render content> }
);
P.S: angle brackets < or >
are not included in the syntax. They are just there as a placeholder for the content that you need to render.
For details, see: React - Conditional Rendering
Alternative
You can use useMemo
, which doesn't wait for re-render
. It will execute same way based on dependencies like useEffect too.
useMemo(()=>{
doSomething() //Doesn't want until render is pleted
}, [dep1, dep2])
本文标签: javascriptMake useEffect hook run before rendering the componentStack Overflow
版权声明:本文标题:javascript - Make useEffect hook run before rendering the component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744026231a2520681.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论