Search code examples
javascriptreactjsreact-hooksrtk-query

Passing a state argument set by useEffect to RTK Query's queryFn


I'm passing in a boolean argument, usingAsSignUp, into the queryFn.

Unfortunately, usingAsSignUp always results in undefined! How do I get it's values? usingAsSignUp is state set by useEffect in the consuming component.

RTK Query createApi with queryFn:

export const firebaseApi = createApi({
  reducerPath: "firebaseApi",
  baseQuery: fakeBaseQuery(),
  tagTypes: ["Auth"], //Optional, https://redux-toolkit.js.org/rtk-query/api/createApi#tagtypes
  endpoints: (builder) => ({
    authenticateWithFirebase: builder.mutation({
      async queryFn({ email, password, usingAsSignUp }) {
        try {
          const auth = getAuth(firebaseApp);
          const userCredential = usingAsSignUp ? 
          await createUserWithEmailAndPassword(auth, email, password) : 
          await signInWithEmailAndPassword(auth, email, password);
          return {
            data: {
              uid: userCredential?.user?.uid,
              email: userCredential?.user?.email,
              usingAsSignUp: usingAsSignUp,
            },
          };
        } catch (e) {
          return { error: e };
        }
      },
      providesTags: ["Auth"], //Optional, https://redux-toolkit.js.org/rtk-query/api/createApi#providestags
    }),
  }),
});

export const { useAuthenticateWithFirebaseMutation } = firebaseApi;

Consuming component using useEffect to set the state passed to queryFn:

  import { useAuthenticateWithFirebaseMutation } from "../../persistence/apiSlices";

  const [signup, setSignup] = useState(true);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const location = useLocation();

  const [authenticateNow, result, data] = useAuthenticateWithFirebaseMutation();

  useEffect(() => {
    location.pathname === "/login" ? setSignup(false) : setSignup(true);
  }, [location.pathname] );

  async function onSubmitACB() {
    await authenticateNow({ email, password, signup });
  }

Solution

  • You are passing a boolean argument usingAsSignUp to the queryFn of your authenticateWithFirebase mutation endpoint, but it always results in undefined. This might be because you are not passing the argument correctly from your component.

    To fix this error, you need to pass usingAsSignUp value as signup to the queryFn of authenticateWithFirebase endpoint in your firebaseApi configuration.

    await authenticateNow({ email, password, usingAsSignUp: signup });