Search code examples
firebaseredux-toolkitreact-tsx

Can we make firebase actions serializable for redux toolkit?


I am using react and redux toolkit in a project. I also use firebase to manage authentication for this project.

I'm dispatching an async thunk that I call login to login users. And here I am calling the signInWithEmailAndPassword method of firebase. I export this method from a file named firebase.ts. You can find code snippets below.

// firebase.ts

import { initializeApp } from "firebase/app";
import {
  getAuth,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signOut,
  sendPasswordResetEmail,
  sendEmailVerification,
  updateEmail,
  updatePassword,
  reauthenticateWithCredential,
  EmailAuthProvider,
} from "firebase/auth";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
  measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID,
};

const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);

export {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signOut,
  sendPasswordResetEmail,
  sendEmailVerification,
  updateEmail,
  updatePassword,
  reauthenticateWithCredential,
  EmailAuthProvider,
};

// UserContent/thunks.ts

import { createAsyncThunk } from "@reduxjs/toolkit";
import { auth, signInWithEmailAndPassword, signOut } from "@app/api/firebase";
import { UserLoginForm } from "@common/formTypes";

export const login = createAsyncThunk(
  "userContent/login",
  async (data: UserLoginForm) => {
    const { email, password } = data;
    const response = await signInWithEmailAndPassword(auth, email, password);
    return response;
  }
);

export const logout = createAsyncThunk("userContent/logout", async () => {
  const response = await signOut(auth);
  return response;
});

But as you can guess in the console, I get a warning like the following.

Console Warning Image

Of course I know I can turn off this warning very easily. But is there a better way to solve this?


Solution

  • You can convert your response to a serializable object by adding .toJson() to the response.

    export const login = createAsyncThunk(
     "userContent/login",
      async (data: UserLoginForm) => {
      const { email, password } = data;
      const response = await signInWithEmailAndPassword(auth, email, password);
      return response.toJSON();
      }
    );