Search code examples
javascriptnode.jsreactjsethereum

API call can't fetch ONLY the value on the backend (nodejs) from front-end (react)


I'm pretty new to backend/frontend stuff and can't find the solution here...

I have a store.js file that store data when the users are interacting with the UI (using zustand).

I have a variable feed that returns something like "0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e".

I'm trying to retrieve it in the backend to make a call to a smart contract function but can't retrieve the data in the correct format.

Here are the codes snipped :

FRONTEND:

import useStore from "../components/store";

export async function getPrice() {
  const { feed } = useStore.getState();

  try {
    const response = await fetch("/api/getPrice", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ feed }),
    });

    const result = await response.json();
}

BACKEND:

exports.getPrice = async (feed) => {
  console.log(feed);

/*  
  const provider = new ethers.providers.JsonRpcProvider(RPC);
  const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
  const contract = new ethers.Contract(CONTRACT, ABI, wallet);

  const price = await contract.getPrice(feed);
  console.log("Price:", price);
*/
};

For now the console is returning :
{ feed: '0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e' }

I would like to only get the address '0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e' and not feed : as then I would have to pass the address to the function to call the smart contract.

How can I solve this?

Updated the code but it didn't work.


Solution

  • In the backend section:

    exports.getPrice = async (feed) => {
      console.log(feed);
    }
    

    You're getting the data in an object called feed. So the basically:

    feed = { feed: '0xD4a33860578De61DBAbDc8BFdb98FD742fA7028' }
    

    So you should try something like this:

    exports.getPrice = async (data) => {
      const { feed } = data; 
      console.log(feed);
    };
    

    Or if you don't want to change the name then: console.log(feed["feed"]);