Search code examples
reactjsgatsby

Mapping array in React JS


In a react / gatsby / wordpress project, I need to pull data from a 3rd party, non-graphql API. I am attempting to parse the data returned from this API and make it available for use with graphql.

I'm following the accepted answer in this post: GatsbyJS getting data from Restful API

The error I'm receiving is: res.data.full_options.map is not a function

Here's my code thus far:

exports.sourceNodes = async ({ actions }) => {
    const { createNode } = actions;

    const fetchJoinOptions = () => axios.get(`https://example.com/path/to/api`)

    const res = await fetchJoinOptions()

    console.log(res.data)

    res.data.full_options.map((option, i) => {

    })
}

console.log(res.data) outputs the following:

{
  join_options: { '76': 'Yearly Membership', '366': 'Halloween Sale - 50% Off!' },
  full_options: {
    '76': {
      optionid: '76',
      siteid: '15',
      networkid: '0',
      deleted: '0',
      enabled: '1',
      orderid: '1',
      option_type_id: '0',
      billerid: '0',
      programid: '0',
      legacy: '0',
      details: [Object]
    },
    '97': {
      optionid: '97',
      siteid: '15',
      networkid: '0',
      deleted: '0',
      enabled: '1',
      orderid: '43',
      option_type_id: '0',
      billerid: '0',
      programid: '0',
      legacy: '0',
      details: [Object]
    },
    '190': {
      optionid: '190',
      siteid: '15',
      networkid: '0',
      deleted: '0',
      enabled: '1',
      orderid: '44',
      option_type_id: '0',
      billerid: '0',
      programid: '0',
      legacy: '0',
      details: [Object]
    }
  },
  default_option: '76',
  special_options: { '236': 'Join with Gift Card' }
}

Here's the error in it's entirety:

 ERROR #11321  PLUGIN

"gatsby-node.js" threw an error while running the sourceNodes lifecycle:

res.data.full_options.map is not a function

  26 |     console.log(res.data)
  27 |
> 28 |     res.data.full_options.map((option, i) => {
     |                           ^
  29 |
  30 |     })
  31 |

File: gatsby-node.js:28:27

Could you please explain how I can map this data?


Solution

  • You need to convert your response in Object.entries or Object.values because getting a response in Object format not Array.

    Object.entries() and Object.values()

    Example :

    Object.entries()

    const object1 = {
        a: 'somestring',
        b: 42
    };
    
    for (const [key, value] of Object.entries(object1)) {
        console.log(`${key}: ${value}`);
    }
    
    // expected output:
    // "a: somestring"
    // "b: 42"
    

    Object.values()

    const object1 = {
        a: 'somestring',
        b: 42,
        c: false
    };
    
    console.log(Object.values(object1));
    // expected output: Array["somestring", 42, false]