#How do I use a hook on initial render?

18 messages · Page 1 of 1 (latest)

true crest
dense grotto
#

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...

timid glacier
dense grotto
#

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

timid glacier
#

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;
}
dense grotto
#

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
timid glacier
#

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

dense grotto
#

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()?

timid glacier
timid glacier