How to use Anchor provider to fetch accounts from Solana program in ReactJS

789 views Asked by At

I am new to blockchain and I found some difficult in my first application with Solana. I use Anchor framework, my program is ok when test in CLI, but when I integrate with front-end (ReactJS), it doesn't work.

I had follow some tutorial. But get errors when fetch accounts using Anchor provider. Here's my code:

const getAllCoupon = useCallback(async () => {
    window.Buffer = Buffer;
    const programID = new PublicKey(idl.metadata.address);

    const opts = {
      preflightCommitment: "processed",
    };

    const connection = new Connection(
      "http://127.0.0.1:8899",
      opts.preflightCommitment
    );

    const { solana } = window;

    console.log('>>>>>>>>>>>>>>>>>>', solana)

    const provider = new AnchorProvider(connection, solana, opts.preflightCommitment);

    const program = new Program(idl, programID, provider);

    console.log('>', program);

    try {
      const result = await program.account.coupon.all();
      console.log('>>', result);
      return [...result];
    } catch (err) {
      console.log(err);
    }
  }, []);

And this is the console log:

error details

I think the "program" init correctly, the wallet (solana) also correct. Don't know why I cannot call .all() method like I called in the "back-end" before. Using Windows when work in front-end.

1

There are 1 answers

0
Jonas H. On

in principal your code looks correct. I just called .all() and it worked. What could be the reason is, that there is no coupon accounts yet on your local validator.

Or maybe that just using window as provider is deprecated. The proper way of connecting to solana now would be using the SolanaWalletAdapter which will let you connect to any Solana wallet. Here is an example: https://github.com/solana-developers/solana-game-starter-kits/blob/main/tiny-adventure/app/pages/index.tsx

And here to code and docs: https://github.com/solana-labs/wallet-adapter

Or you can also use npx create-solana-dapp (https://github.com/solana-developers/create-solana-dapp) which will create you a project with wallet adapter already setup.

Also you may get faster help on https://solana.stackexchange.com/