2

Why am I receiving null value when I'm trying to fetch data from an external API?

This is my code

resolvers.js

import fetch from 'node-fetch'

export const resolvers = {
  Query: {
    getCrypto: async() => {
      const response = await fetch(`https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=USD`)
      return response.json();

    }
  },
};


schema.grapqhl

type CryptoCurrency {
  Id: ID
  Name: String
  FullName: String
  PRICE: Float
  LASTUPDATE: Float
}

type Query {
  getCrypto: CryptoCurrency
}


Screenshot of the error:
enter image description here

Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
Pep
  • 97
  • 1
  • 2
  • 9
  • What happens when you browse to the url used? – Jeroen Heier Jan 19 '20 at 07:08
  • There's a mismatch between the shape of the object returned by the API you are getting your data from and the shape of your schema. See Common Scenario #1 and Common Scenario #3 [here](https://stackoverflow.com/a/56319138/6024220). – Daniel Rearden Jan 19 '20 at 07:54

1 Answers1

1

Your API returns an array, so should change your code like below.(for the first item)

 getCrypto: async () => {
        const response = await fetch(`https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=USD`)

        let data = await response.json()
        return data.Data[0].CoinInfo;
            }

Or if you intend to retrieve all names, first change your Query to accept as an array

type Query {
  getCrypto: [CryptoCurrency]
}


 getCrypto: async () => {
        const response = await fetch(`https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=USD`)

           let data = (await response.json()).Data.map(c => { return c.CoinInfo })


        return data

    }
Alex
  • 3,941
  • 1
  • 17
  • 24
  • Added ``return data.Data[0].CoinInfo``` and It worked Alex, Thank you for the help – Pep Jan 19 '20 at 13:56
  • 1
    Your welcome, but be aware that Your API returns an array so you can have 0,1,2,..n index – Alex Jan 19 '20 at 13:58