Skip to content
Advertisement

my react function hook not returning data state inside a function?

this is my function hook:

const useSignIn = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const signUp = useCallback(async ({ email, password, confirmPassword }) => {
    try {
      setLoading(true);
      const response = await api.post("/auth/sign_up/", {
        email,
        password,
        password_confirmation: confirmPassword,
      });
      setData(response.data);
      console.log("signUp response", response.data);
    } catch (error) { 
      if (
        error.response &&
        error.response.data &&
        error.response.data.errors &&
        error.response.data.errors.email
      ) {
        setError(error.response.data.errors.email[0]);
      } else setError("Something went wrong");
    } finally {
      setLoading(false);
    }
  }, []);
  return { loading, signUp, error, data };
};

then i use it in my react hook component like this:

  const { signUp, error: signUpError, loading, data } = useSignUp();

  const onSubmit = async ({
    email,
    password,
    confirmPassword,
  }: InitialValues) => {
    await signUp({ email, password, confirmPassword });
    console.log("data 0 ", data); 

but what happens after signUp is resolved is that data is null? why is it that data is null? my log has data in it but just not on my component

Advertisement

Answer

Because the data you’re looking at (the one you’ve logged) is the one from the previous render.

Instead, use data when rendering (when loading isn’t true) and your component will be called to re-render when data changes — whereupon it will get a new copy of data from useSignup.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement