0

I am pretty new to ReactJS and am trying to figure out why I am not able to display the fetched data. Checked the data in Postman and it is as expected so I am sure there is something syntactical I am missing. I didnt put the key value in this post.

import React, { Component } from 'react'

class Stockstuff extends Component {
    constructor(props) {
        super(props);
        this.state = {
          error: null,
          isLoaded: false,
          items: []
        };
      }

      componentDidMount() {
        fetch("https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=TSLA&apikey=???")
          .then(res => res.json())
          .then(
            (result) => {
              this.setState({
                isLoaded: true,
                items: result.items
              });
            },

            (error) => {
              this.setState({
                isLoaded: true,
                error : true
              });
            }
          )
      }


      render() {
        const { error, isLoaded, items } = this.state;
        if (error) {
          return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
          return <div>Loading...</div>;
        } else {
          return (
            <ul>
              {items.map(item => (
                <li key={item.name}>
                  {item.name} {item.price}
                </li>
              ))}
            </ul>
          );
        }
      }
}

export default Stockstuff

What is the fault?

7
  • Your code is correct, but the URL API just returns error. Commented Feb 22, 2020 at 19:07
  • @AmerllicA, the apikey in the query string is replaced by ???. @Ross Lamon, What is the expected payload? Commented Feb 22, 2020 at 19:13
  • @AmerllicA, how can you possibly know that the code is correct? What if items is not an iterable? Commented Feb 22, 2020 at 19:19
  • Dear @entiendoNull, exactly right, I assume the items exist on the response and it is an iterable object. The code is correct. the issue is not about ReactJS. Commented Feb 22, 2020 at 19:28
  • NEVER email your code to someone who appears to be trying to help. Commented Feb 22, 2020 at 19:33

3 Answers 3

1

The endpoint returns an object, not an array, that's why you can't map over it.

I open this URL from code https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=TSLA&apikey=???

Although it’s strange that it works with apikey=??? for me and I can see something like:

{
    "Meta Data": {
        "1. Information": "Monthly Prices (open, high, low, close) and Volumes",
        "2. Symbol": "TSLA",
        "3. Last Refreshed": "2020-02-21",
        "4. Time Zone": "US/Eastern"
    },
    "Monthly Time Series": {
        "2020-02-21": {
            "1. open": "673.6900",
            "2. high": "968.9899",
            "3. low": "673.5200",
            "4. close": "901.0000",
            "5. volume": "377921898"
        },
        "2020-01-31": {
            "1. open": "424.5000",
            "2. high": "653.0000",
            "3. low": "421.7100",
            "4. close": "650.5700",
            "5. volume": "407621638"
        },
        [...]
    }
}

I slightly changed the code to match the data and everything seems fine:

https://codesandbox.io/s/red-mountain-ipn3h

Sign up to request clarification or add additional context in comments.

Comments

0

I looked at the api endpoint and the structure of the data has no items key. So when you say results.items it's not returning anything. It looks like the two top-level keys for the object that is returned are "Meta Data" and "Monthly Time Series". You can't use dot notation for keys with spaces, so assuming you want the "Monthly Time Series" data, you'd want to do:

          ...

          .then(
            (result) => {
              this.setState({
                isLoaded: true,
                items: result["Monthly Time Series"]
              });
            },

          ...

ETA: it also doesn't return an array so you won't be able to use .map in your render function.

1 Comment

You pass half way.
0

Write your code like below:

import React, { Component } from 'react'

class Stockstuff extends Component {
    constructor(props) {
        super(props);
        this.state = {
          error: null,
          isLoaded: false,
          items: []
        };
      }

      componentDidMount() {
        fetch("https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=TSLA&apikey=???")
          .then(res => res.json())
          .then(
            (result) => {
              this.setState({
                isLoaded: true,
                items: Object.entries(result['Monthly Time Series'])
              });
            },

            (error) => {
              this.setState({
                isLoaded: true,
                error : true
              });
            }
          )
      }


      render() {
        const { error, isLoaded, items } = this.state;
        if (error) {
          return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
          return <div>Loading...</div>;
        } else {
          return (
            <ul>
              {items.map(item => (
                <li key={item[0]}>
                  <span>{item[1].open}</span>
                  <span>{item[1].high}</span>
                  <span>{item[1].low}</span>
                  <span>{item[1].close}</span>
                  <span>{item[1].volume}</span>
                </li>
              ))}
            </ul>
          );
        }
      }
}

export default Stockstuff;

3 Comments

Hey, you just posted a "slightly changed" version of my code from codesendbox example. Is this okay on StackOverflow? 🤔
Dear comrade @artanik, I didn't see your code yet. I just write my sight. If you think I steal your codes, please flag my post and report it. But I swear I didn't see your link yet.
I won't flag your answer, apparently Object.entries is an obvious answer to this question and you also came up with this idea, and that's totally fine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.