0

I'm building an Identification management dApp, in which I have to redirect to a different component based on selected MetaMask account address.

For example, if I'm an applicant then I will be redirected to ./applicant when I connect to my particular MetaMask account.

This is my app.jsx :

import { useState, useEffect } from "react";
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link,
  Navigate,

} from "react-router-dom";
import { ethers } from "ethers";
import abi from "./contractJson/chai.json";
import PInfo from "./components/frontend/PInfo";
import GInfo from "./components/backend/GInfo";
import Edit from "./components/frontend/requEdit";
import Ap from "./components/Appli";
import NI from "./components/frontend/NIDsta";
import LOG from "./components/LocalGov";
import NID from "./components/frontend/getNID";
import GEDIT from "./components/backend/getEdit"
import WEL from "./components/welcome"
import "./App.css";

function App() {
  const [state, setState] = useState({
    provider: null,
    signer: null,
    contract: null,
  });

  const [account, setAccount] = useState("");

  useEffect(() => {
    const initialize = async () => {
      const contractAddress = "0xdaAE5bF9F3f8146584876ad0608E52Dd50bB82CB";
      const contractABI = abi.abi;

      try {
        if (!window.ethereum) {
          alert("Please install MetaMask!");
        }
        const { ethereum } = window;
        const accounts = await ethereum.request({
          method: "eth_requestAccounts",
        });

        window.ethereum.on("accountsChanged", () => {
          window.location.reload();
        });
        setAccount(accounts[0]);

        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();

        const contract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );
    
        // console.log(contract);
        setState({ provider, signer, contract });
          
 

      
      } catch (error) {
        alert(error.message || "Error occurred while initializing.");
      }
    };
    initialize();

    const redirectBasedOnAccount = (account) => {

      if (account === "0x1613d968665C978C3a5b7A08653185377DFbEDb8") {
        console.log("In redirection")
        return <Navigate to="/applicant" replace />;
      } else if (account === "0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65") {
        return <Navigate to="/LocalGov" replace />;
      }
      // Handle other accounts or default route if not matched
     
    };

    redirectBasedOnAccount(account)
  }, [account]);

   
 
  

  return (
    <>
        
      <Routes>
        <Route path="/" element={<WEL></WEL>}></Route>
        <Route path="/applicant" element={<Ap></Ap>}></Route>
        <Route path="/LocalGov" element={<LOG></LOG>}></Route>


        <Route path="/apply" element={<PInfo state={state} />}></Route>

        <Route path="/admin" element={<GInfo state={state} />}></Route>
        <Route path="/RequestEdit" element={<Edit></Edit>}></Route>
        <Route path="/Status" element={<NI></NI>}></Route>
        <Route path="/getnid" element={<NID></NID>}></Route>
        <Route path="/getEditInfo" element={<GEDIT></GEDIT>}></Route>
      </Routes>

   
    </>
  );
}

export default App;

I have tried this function:

const redirectBasedOnAccount = (account) => {

      if (account === "0x1613d968665C978C3a5b7A08653185377DFbEDb8") {
        console.log("In redirection")
        return <Navigate to="/applicant" replace />;
      } else if (account === "0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65") {
        return <Navigate to="/LocalGov" replace />;
      }
      // Handle other accounts or default route if not matched
     
    };
 import React, { useState } from "react";
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link,
  Navigate,
  useNavigate
} from "react-router-dom";

const Appli = ({ state, account }) => {

  const [navigateTo, setNavigateTo] = useState(null);
    


  if (account === "0x1613d968665C978C3a5b7A08653185377DFbEDb8") {
    return (
      <>
        <nav>
          <ul>
            <li>
            <Link >Apply Now</Link>
            </li>
            <li>
              <Link to="/RequestEdit">Reuest For Edit </Link>
            </li>
            <li>
              <Link to="/Status"> Check Status</Link>
            </li>
            <li>
              <Link to="/getnid"> Get NID</Link>
            </li>
          </ul>
        </nav>
      </>
    );
  }
  
};

export default Appli;

this is my appli.jsx file But, it's still not working.

Here's my GitHub repo containing the full project.

3
  • Kindly please accept the previous answer as well as this answer, if they helped you out, so that they can be helpful for others facing the similar problem as well. Commented May 18 at 23:39
  • Hi , did already, I was struglling , they seems to have issue for me to accept answer with low repuataions
    – Shorna
    Commented May 19 at 1:25
  • Okay. No worries. Thanks. Commented May 19 at 1:46

1 Answer 1

1

Instead of defining and calling your redirectBasedOnAccount function inside useEffect. You need to define it outside its scope, and call the same inside the return of your App.jsx.

Also, you need to convert the addresses to lowercase while comparing, because the eth_requestAccounts returns the account addresses in lowercase.

Here's the revised code for App.jsx:

import { useState, useEffect } from "react";
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link,
  Navigate,

} from "react-router-dom";
import { ethers } from "ethers";
import abi from "./contractJson/chai.json";
import PInfo from "./components/frontend/PInfo";
import GInfo from "./components/backend/GInfo";
import Edit from "./components/frontend/requEdit";
import Ap from "./components/Appli";
import NI from "./components/frontend/NIDsta";
import LOG from "./components/LocalGov";
import NID from "./components/frontend/getNID";
import GEDIT from "./components/backend/getEdit"
import WEL from "./components/welcome"
import "./App.css";

function App() {
  const [state, setState] = useState({
    provider: null,
    signer: null,
    contract: null,
  });

  const [account, setAccount] = useState("");


  useEffect(() => {
    const initialize = async () => {
      const contractAddress = "0xdaAE5bF9F3f8146584876ad0608E52Dd50bB82CB";
      const contractABI = abi.abi;

      try {
        if (!window.ethereum) {
          alert("Please install MetaMask!");
        }
        const { ethereum } = window;
        const accounts = await ethereum.request({
          method: "eth_requestAccounts",
        });

        window.ethereum.on("accountsChanged", () => {
          window.location.reload();
        });
        setAccount(accounts[0]);

        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();

        const contract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );

        // console.log(contract);
        setState({ provider, signer, contract });




      } catch (error) {
        alert(error.message || "Error occurred while initializing.");
      }
    };
    initialize();
  }, [account]);


  const redirectBasedOnAccount = (account) => {

    if (account === "0x1613d968665C978C3a5b7A08653185377DFbEDb8".toLowerCase()) {
      console.log("In redirection")
      return <Navigate to="/applicant" replace />;
    } else if (account === "0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65".toLowerCase()) {
      return <Navigate to="/LocalGov" replace />;
    }
    // Handle other accounts or default route if not matched

  };


  return (
    <>

      {redirectBasedOnAccount(account)}

      <Routes>
        <Route path="/" element={<WEL></WEL>}></Route>
        <Route path="/applicant" element={<Ap></Ap>}></Route>
        <Route path="/LocalGov" element={<LOG></LOG>}></Route>


        <Route path="/apply" element={<PInfo state={state} />}></Route>

        <Route path="/admin" element={<GInfo state={state} />}></Route>
        <Route path="/RequestEdit" element={<Edit></Edit>}></Route>
        <Route path="/Status" element={<NI></NI>}></Route>
        <Route path="/getnid" element={<NID></NID>}></Route>
        <Route path="/getEditInfo" element={<GEDIT></GEDIT>}></Route>
      </Routes>


    </>
  );
}

export default App;
5
  • It works , thanks a lot
    – Shorna
    Commented May 19 at 1:26
  • You're welcome. Happy coding! Commented May 19 at 1:46
  • I hope this will find you I am not a react expert trying to improve can you see this one ``` return <Navigate to="/applicant" replace />; when I am navigating to /applicant the applicant component has 4 links /apply ,/editreauest like this when I click on apply now it wont let me to redirectted to /apply as I am navigateed to /applicant connecting to a account How can I fix this , I used several approach not working like useNavigate
    – Shorna
    Commented May 24 at 8:46
  • I have added my appli.jsx file in the question
    – Shorna
    Commented May 24 at 8:51
  • @Shorna, I've answered. Please check. Commented Jun 2 at 3:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.