0

I'm using redux and web3auth with nextjs. But i'm encountering state mutation error in many places. this codebase used to work properly on reactjs. This error occurs sometimes and don't let me proceed with my application flow. And sometime it doesn't create any barrier or doesn't even appear. absolutely clueless how to solve this.

Error: Invariant failed: A state mutation was detected between dispatches, in the path 'web3authInfo.web3authInstance.walletAdapters.openlogin.openloginInstance.currentStorage.storage.persist:nextjs'. This may cause incorrect behavior.

Below is the connect function. the error is occuring from the catch of this function.

const connect = async () => {
    console.log("Hello");
    setIsLoading(true);
    try {
      const web3auth = new Web3Auth({
        clientId: process.env.CLIENT_ID,
        chainConfig: {
          chainNamespace: "eip155",
          chainId: "0x5", 
        },
        web3AuthNetwork: "mainnet",
      });

      await web3auth.initModal();

      await web3auth.connect();
      const user = await web3auth.getUserInfo();

      //   console.log("user:", user);
      const isEmpty = Object.keys(user).length === 0;
      console.log(user, " user", isEmpty);

      if (isEmpty) {
        console.log("no user");
        setIsLoading(false);
        await handleWeb3Logout(web3auth, dispatch);
      }

      const app_scoped_privkey = await web3auth.provider?.request({
        method: "eth_private_key", 
      });
      console.log(app_scoped_privkey, " app scoped private key");
      saveWeb3Instance(dispatch, web3auth);
      if (typeof app_scoped_privkey === "string") {
        const app_pub_key = getPublicCompressed(
          Buffer.from(app_scoped_privkey.padStart(64, "0"), "hex")
        ).toString("hex");
        console.log(app_pub_key, app_scoped_privkey, " apppppp key");

        console.log(user.idToken, " id token id token", user);

        const postRes = await web3authApi(
          dispatch,
          setStatusCode,
          setEmail,
          app_pub_key,
          user.idToken,
          web3authInfo.web3authInstance
        );
      }
    } catch (err) {
      console.log("connect error", err);
    }
  };

This is my web3reducer.js file.

const initialState = {
  web3authInstance: null,
  walletAddress: null,
};

export const web3authReducer = (state = initialState, action) => {
  switch (action.type) {
    case "SET_WEB3AUTH_INSTANCE":
      return { ...state, web3authInstance: action.payload };
    case "SET_WALLET_ADDRESS":
      return { ...state, walletAddress: action.payload };
    case "DISCONNECT_WEB3AUTH":
      return {
        ...state,
        web3authInstance: null,
        walletAddress: null,
      };
    default:
      return state;
  }
};

web3action.js file:

import { RESPONSE_MESSAGE } from "../../utils/message";
import { getSigner } from "@src/function/web3Functions";

export const setWeb3AuthInstance = (web3authInstance) => {
  return async (dispatch) => {
    try {
      dispatch({
        type: "SET_WEB3AUTH_INSTANCE",
        payload: web3authInstance,
      });
    } catch (error) {
      console.error("Error from redux web3authInstance:", error);
    }
  };
};

export const setWalletAddress = (web3authInstance) => {
  return async (dispatch) => {
    try {
      const signer = await getSigner(web3authInstance);
      const walletAddress = await signer.getAddress();

      dispatch({
        type: "SET_WALLET_ADDRESS",
        payload: walletAddress,
      });
    } catch (error) {
      console.error("Error from redux wallet address:", error);
    }
  };
};

export const disconnectWeb3Auth = () => {
  return {
    type: "DISCONNECT_WEB3AUTH",
  };
};

I'm unable to understand why this error is occuring and how to solve. but this is hampering the flow of my application. Please help me solve this issue.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • You should not store a class instance like this in Redux. Redux is for static data where Redux controls when data changes, and only in a reducer. That web3authInstance is a dynamic class incstance that changes itself on it's own with different timing - hence the error message. – phry Jul 16 '23 at 07:09
  • But I need this instance value again for logout. how can I store this for logout then? – jakiatalks Jul 16 '23 at 07:49
  • Redux is there for data, for something that is not data like this, you should probably have a wrapper component that keeps it in component state and passes it around with a dependency injection mechanism like Context. – phry Jul 16 '23 at 08:55
  • @zacanger Just FYI, adding tags to posts isn't how code syntax highlighting works, you need to actually edit the post's code block fences to specify a language. – Drew Reese Jul 17 '23 at 06:12

0 Answers0