#How do I use a hook on initial render?
18 messages · Page 1 of 1 (latest)
this just looks like an improperly built component/hook
export default function Sidebar() {
const navigate = useNavigate();
const user = useGetUser();
...
}
you don't store the user as a local state variable in the sidebar...
Are you saying I'm meant to store it as a local variable instead of storing it in useState?
yes, as I showed. if you need a setUser(), you put it in the useGetUser() hook (and return it along with user).
I guess the confusion is because useGetUser() is also built incorrectly
So it should be like this?
// Utilities.jsx
export async function useGetUser() {
const [user, setUser] = useState();
const navigate = useNavigate();
useEffect(() => {
let res = await fetch("http://localhost:3000/auth/user", {
credentials: "include",
});
if (!res.ok) navigate("/auth");
const user = await res.json();
setUser(user);
}, [])
return user;
}
// Sidebar.jsx
export default function Sidebar() {
const navigate = useNavigate();
const user = useGetUser();
useIsAuthenticated();
return (
// ...
)
}
Could I instead write useGetUser like this?
// Utilities.jsx
export async function useGetUser() {
const navigate = useNavigate();
let res = await fetch("http://localhost:3000/auth/user", {
credentials: "include",
});
if (!res.ok) navigate("/auth");
const user = await res.json();
return user;
}
no
export function useGetUser() {
const navigate = useNavigate();
const [user, setUser] = useState();
useEffect(() => {
fetch("http://localhost:3000/auth/user", {
credentials: "include",
}).then(res => {
if (!res.ok) navigate("/auth");
return res.json();
}).then(data => {
setUser(data);
});
}, []);
return user;
}
- data/state is stored in the custom hook
- you cannot make effects async
So this works for the Sidebar, but what if I want to use useGetUser() in another component and it gets rerendered but the user doesn't change, then it needlessly gets the user again
no it doesn't
try it
no clue what useIsAuthenticated() is, but it's probably also a problem
why wouldn't that be part of useGetUser()?
Ohh you are right, I thought it would, thank you :)
Yeah I need to fix this next 😅