Home > Back-end >  TSX React - How to index JSON API Data with multiple JSON Objects
TSX React - How to index JSON API Data with multiple JSON Objects

Time:12-29

I am trying to use useFetch to get API data and index to get a specific value.

This is the current code:

const { isLoading, error, data } = useFetch("https://public-api.solscan.io/account/tokens?account=C9XzDbZrZkJ75EvEeb641PQ5Q9kDiN2nFugdyAXqGip1");
  const dataStarsStaked = JSON.stringify(data, ["0", "tokenAddress", "tokenAmount", "uiAmount"], 0);

which returns data:

[{"tokenAddress":"4q5UBXJxE91BZKX548qhU8i5QBWvZdXzS3RZwfTgLQda","tokenAmount":{"uiAmount":253847.899902}},{"tokenAddress":"HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW","tokenAmount":{"uiAmount":6864373.022357}},{"tokenAddress":"HkNK7BL5pSUUzc6ns1mHW5JnzbSG4S9u2QdR3cUuyzSa","tokenAmount":{"uiAmount":678}}]

I am trying to get the value of uiAmount of tokenAddress: HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW. How do I do this? I am not sure how to index this. Thanks!

CodePudding user response:

You can search the data array:

data.find(x => x.tokenAddress === "HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW");

To get rid of the typescript errors, you need to define types (use something similar to this, but change any[] to the array of object types the api is returning):

interface YourFetchResult {
   data: any[];
   isLoading: boolean;
   error?: string;
}

const { isLoading, error, data }: FetchResult = useFetch(...)

CodePudding user response:

you need to apply a for loop and have a condition that detects the string see below

  let x  = [{"tokenAddress":"4q5UBXJxE91BZKX548qhU8i5QBWvZdXzS3RZwfTgLQda","tokenAmount":{"uiAmount":253847.899902}},{"tokenAddress":"HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW","tokenAmount":{"uiAmount":6864373.022357}},{"tokenAddress":"HkNK7BL5pSUUzc6ns1mHW5JnzbSG4S9u2QdR3cUuyzSa","tokenAmount":{"uiAmount":678}}]
  
  for (let i = 0; i < x.length; i  ) {
    if(x[i].tokenAddress==="HCgybxq5Upy8Mccihrp7EsmwwFqYZtrHrsmsKwtGXLgW") {
      console.log(x[i].tokenAmount)
    }
  
  }
  • Related