haredev
haredev

Reputation: 87

Parsing JSON into an array of objects for React state hook

I have a react hook component that queries an API and gets a json response. Here is the result

import React, {useEffect, useState} from 'react';
import axios from 'axios';
const fetch = () => axios({
      "method": "GET",
      "url": "https://rest.coinapi.io/v1/assets",
      "headers": {
        "X-CoinAPI-Key": process.env.REACT_APP_API_KEY
      },
      "params":{
        filter_asset_id:'ADA,DOGE'

      }
    })
    .then(resp => resp.data);
function App() {
  const [responseData, setResponseData] = useState('');

  const doFetch = () => fetch()
    .then(setResponseData)
    .catch(console.log)
  
  useEffect(doFetch, []);

This returns the following response:

import React, {useEffect, useState} from 'react';
import axios from 'axios';
const fetch = () => axios({
      "method": "GET",
      "url": "https://rest.coinapi.io/v1/assets",
      "headers": {
        "X-CoinAPI-Key": process.env.REACT_APP_API_KEY
      },
      "params":{
        filter_asset_id:'ADA,DOGE'

      }
    })
    .then(resp => resp.data);
function App() {
  const [responseData, setResponseData] = useState('');

  const doFetch = () => fetch()
    .then(setResponseData)
    .catch(console.log)
  
  useEffect(doFetch, []);
[

{


"asset_id": "DOGE",


"name": "DogeCoin",


"type_is_crypto": 1,


"data_start": "2014-02-21",


"data_end": "2021-02-14",


"data_quote_start": "2014-07-31T13:05:46.0000000Z",


"data_quote_end": "2021-02-14T18:22:14.0444958Z",


"data_orderbook_start": "2014-07-31T13:05:46.0000000Z",


"data_orderbook_end": "2020-08-05T14:37:58.7197513Z",


"data_trade_start": "2014-02-21T05:16:16.8330000Z",


"data_trade_end": "2021-02-14T18:22:19.5790000Z",


"data_symbols_count": 5087,


"volume_1hrs_usd": 959931643063215.5,


"volume_1day_usd": 24555251931853564,


"volume_1mth_usd": 1164688438619710000,


"price_usd": 0.0582213,


"id_icon": "63e240f3-047f-41c7-9179-6784bc719f63"

},

{


"asset_id": "ADA",


"name": "Cardano",


"type_is_crypto": 1,


"data_start": "2017-09-29",


"data_end": "2021-02-14",


"data_quote_start": "2017-09-29T07:11:06.6463948Z",


"data_quote_end": "2021-02-14T18:22:15.5083587Z",


"data_orderbook_start": "2017-09-29T07:11:06.6463948Z",


"data_orderbook_end": "2020-08-05T14:37:58.7010000Z",


"data_trade_start": "2017-10-01T20:08:31.0000000Z",


"data_trade_end": "2021-02-14T18:23:14.3000000Z",


"data_symbols_count": 291,


"volume_1hrs_usd": 26528901139214.32,


"volume_1day_usd": 674063191501356.9,


"volume_1mth_usd": 19627652476847524,


"price_usd": 0.8355325,


"id_icon": "2701173b-1b77-40f2-8693-9659359e225c"

}
]

I want to have the data structured like so with "asset_id" as the key and "price_usd" as a value like so:

[{label:'DOGE',value:'0.0582213'},{label:'ADA', value:'0.8355325'}]

I'm not sure where to manipulate the data, and how to do so. Here is my attempt:

import React, {useEffect, useState} from 'react';
import axios from 'axios';
const fetch = () => axios({
      "method": "GET",
      "url": "https://rest.coinapi.io/v1/assets",
      "headers": {
        "X-CoinAPI-Key": process.env.REACT_APP_API_KEY
      },
      "params":{
        filter_asset_id:'ADA,DOGE'

      }
    })
    .then(resp => resp.data);
function App() {
  const [responseData, setResponseData] = useState('');

  const doFetch = () => fetch()
    .then(setResponseData)
    .catch(console.log)
  
  useEffect(doFetch, []);
  useEffect(()=>{
var arr = responseData.map(obj => ({
    key: responseData.asset_id,
    sortable: true,
    resizeable: true
}))};

I realize that even if I got that map function to work, it would have asset_id as key with ALL the values of the API response data, not just price_usd.

Upvotes: 0

Views: 550

Answers (2)

Iman Tahriri
Iman Tahriri

Reputation: 67

You can do it in a chained then both in your axios call or after fetch.

const doFetch = () => fetch()
  .then(data => {
   /* manipulate data here */
   return manipulatedData;
   })
  .then(setResponseData)
  .catch(console.log)

Upvotes: 0

Mellet
Mellet

Reputation: 1306

Try something like this.

Should console.log out:

[
  { label: "DOGE", value: 0.0582213 },
  { label: "ADA", value: 0.8355325 }
] 

Code:

const fetchCryptoData = async () => {
  const response = await axios({
    method: "GET",
    url: "https://rest.coinapi.io/v1/assets",
    headers: {
      "X-CoinAPI-Key": process.env.REACT_APP_API_KEY,
    },
    params: {
      filter_asset_id: "ADA,DOGE",
    },
  })

  const coins = response.data.map(coinApiData => ({
    label: coinApiData.asset_id,
    value: coinApiData.price_usd,
  }));

  return coins;
}

function App() {
  const [coins, setCoins] = useState([]);

  useEffect(() => {
    fetchCryptoData().then(setCoins);
  }, []);

  console.log(coins);

  return null;
}

Upvotes: 1

Related Questions