Parsing JSON from API Response

Hi!

I’m attempting to use the Stripe API. I want to just extract the product name for the JSON object I get back.

I can print to console and I get the following JSON object:

Here’s the code on the page:

import React from 'react'

export default class Products extends React.Component {
  state = {
    content: 'loading...'
  }
  async componentDidMount() {
      if (typeof fetch == 'undefined') return
      const response = await fetch('/.netlify/functions/products')
      const content = await response.json()

      console.dir({ content })

      this.setState({ content: JSON.stringify(content) })
    }
  render() {
    const { content.products } = this.state
    return (
      <div style={{ color: 'white' }}>
        <h2>Data received from <code>/.netlify/functions/products/</code>:</h2>
        <p>content.products.data[0].metadata.name</p>
        <br />
        <br />
        <br />

      </div>
    )
  }
}

To me, it looks like the following code should access the product name:

content.products.data[0].metadata.name

or

content.products.data[0].name

I am trying to just get the product name. Instead, I get an output of the entire object:

{"products":{"object":"list","data":[{"id":"prod_EzVExr5aLjvMtV","object":"product","active":true,"attributes":["name"],"caption":null,"created":1556770137,"deactivate_on":[],"description":null,"images":[],"livemode":true,"metadata":{},"name":"Precise Parasite Home Test Hit","package_dimensions":null,"shippable":true,"skus":{"object":"list","data":[{"id":"sku_EzVERiWpvoz0or","object":"sku","active":true,"attributes":{"name":"Precise Parasite Home Test Hit"},"created":1556770137,"currency":"usd","image":"https://files.stripe.com/links/fl_live_MBnxbXpVarp0VElEaPUrwlBz","inventory":{"quantity":null,"type":"infinite","value":null},"livemode":true,"metadata":{},"package_dimensions":null,"price":19500,"product":"prod_EzVExr5aLjvMtV","updated":1556770137}],"has_more":false,"total_count":1,"url":"/v1/skus?product=prod_EzVExr5aLjvMtV&active=true"},"type":"good","updated":1556771045,"url":null}],"has_more":false,"url":"/v1/products"}}

But I just want to output the product name.

What am I doing wrong?

Thank you!

Take a look at the Free Code Camp ES6 curriculum on destructuring nested objects. If you don’t want to use destructuring, then look at the Basic JavaScript section on Accessing Nested Objects. There are some other challenges in those sections which could also help you.

2 Likes

Why you parse it then stringify the content again?

The above is not how you destructure this.state to get the property `products`.

I agree with @tkhquang, you just need to write:

this.setState({ content });

Then, if you only need the name property of the first element of the data array, you could use:

const { content: {products: { data: [ { name: productName } ] } } } = this.state;
console.log(productName); // displays 'Precise Parasite Home Test Hit'

If you need to iterate through the data array, then you would do:

const { content: { products: { data } } } = this.state;
data.map(({ name }) => name); // ['name1', 'name2', ... ]
1 Like

Thank you for pointing this out.

I was using code from another person without understanding it!

I will study up to get better.

Thank you - I will look into these course.

Btw Qunincy said you’re a prolific contributor, thank you for helping people like me <3

I marked this as the solution, but I couldn’t get it to work.

I don’t have enough background outside of vanilla JS to understand this. I’m going to try and take those courses you recommended to figure out how to understand what I should do.

Can you share the code you say does not work? I can take a look at it and give you some more feedback.

Okay thanks Randell.

So I’m making a gatsby React app, and I can’t get it to compile since I made the changes.

Here’s the error messages I got:

ERROR in ./src/pages/test-products.js
Module Error (from ./node_modules/eslint-loader/index.js):

C:\Users\dude\desktop\test-repo\stripe-backend\src\pages\test-products.js
  26:13  error  'content' is not defined  no-undef

? 1 problem (1 error, 0 warnings)

 @ ./.cache/sync-requires.js 34:62-154
 @ ./.cache/app.js
 @ multi (webpack)-hot-middleware/client.js?path=/__webpack_hmr&reload=true&overlay=false C://Users//dude//desktop//test-repo//stripe-backend//.cache//app
i ?wdm?: Failed to compile.

Here’s what I have:

import React from 'react'

export default class Products extends React.Component {
  state = {
    content: 'loading...'
  }
  async componentDidMount() {
      if (typeof fetch == 'undefined') return
      const response = await fetch('/.netlify/functions/products')
      const content = await response.json()

      console.dir({ content })

      //const { content: {products: { data: [ { name: productName } ] } } } = this.state;
      //console.log(productName);


      this.setState({ content })
    }
  render() {

    return (
      <div style={{ color: 'white' }}>


        <p>{content}</p>
        <br />
        <br />
        <br />

      </div>
    )
  }
}

Any suggestions on where I went wrong?

Thank you

What does the above yield?

It doesn’t compile so I can’t see. It’s react gatsby.

Hi, I think it should be <p>{this.state.content}</p>