Using the Backend Declaration in the Frontend

I am continuing to have issues calling a backend method in a frontend canister (based on React). After referencing the tutorials particularly the custom_greeting (Hello World) tutorial and Best way to use generated declarations in JS / reactJS frontend? - #10 by p_d, I am able to infer the following.

I can import the declarations file created for my backend into the frontend component:

import { backend } from "../declarations/backend";

Let’s pretend that my declaration file for my backend is the following:

service: () -> {
    getAllId: () -> (vec record {id:text}) query;
}

I am trying to then add this code to the my frontend component:

 useEffect(() => {
    async function fetchIds() {
      try {
        const ids = await backend.getAllId();
        return ids;
      } catch (error) {
        console.error("Error fetching ids:", error);
      }
    }
    fetchIds();
  }, []);

I receive the following error:

Error fetching ids: TypeError: Cannot convert a BigInt value to a number

What could I be doing wrong?

I found the error that is causing this. The agent is unaware of which backend canister to call. This is related to this question posted here.

Since a React application created from create-react-app requires REACT_APP_ appended on an environment variable, whenever I run dfx, the agent automatically updates to call the canister Id environment variable without the REACT_APP_ appended.

For example, whenever I run dfx deploy, the following file tied to the JS agent is automatically generated .dfx/local/canisters/backend/index.js and calls the following environment variable:

export const canisterId = process.env.BACKEND_CANISTER_ID;

One way to resolve this is to include the dot-env package in the file which requires an update to the dfx package.

Has anyone found a better solution?

I’ve done something like this
https://github.com/infu/nftanvil/blob/main/oapps/nftanvil_frontend/dfx.ic.env.js
you can just generate the files
.env.development.local
and
.env.production.local
based on the files dfx generates.
Most probably you don’t need a lot of the code in there

1 Like