0

I am trying to map the data I get back from an API in this format:

data={[
    { x: 0, y: 0 },
    { x: 1, y: 1 },
    { x: 2, y: 2 },
    { x: 3, y: 3 },
    { x: 4, y: 4 },
  ]}

I have a get call then I map each of the items to give me an x , y value:

getCryptoChartData('histohour', selectedCrypto, 24, 1).then(
          cryptoChartData => {
            //const response = cryptoChartData.Data.map(item => item.close);
            const data = cryptoChartData.Data.map(item => {
              [
                {
                  x: item.time,
                  y: item.close,
                },
              ];
            });
            return this.setState({cryptoChartData: data});
          },
        );

However, I notice that the data array is set to undefined:

<SlideAreaChart
 data={this.state.cryptoChartData}
/>

Am I setting the data array correctly with the mapping?

1 Answer 1

1

Yes, it seems the problem is in mapping. You just forget to return the generated object:

    const data = cryptoChartData.Data.map(item => {
      return {
          x: item.time,
          y: item.close,
      };
    });

or

const data = cryptoChartData.Data.map(item => ({
    x: item.time,
    y: item.close,
}));

Final code of getCryptoChartData method will look like:

getCryptoChartData('histohour', selectedCrypto, 24, 1)
    .then(cryptoChartData => {
        const data = cryptoChartData.Data.map(item => ({
            x: item.time,
            y: item.close,
        }));
        this.setState({ cryptoChartData: data });
    });
Sign up to request clarification or add additional context in comments.

5 Comments

But I am doing this return this.setState({cryptoChartData: data});
You don't need that return. You need to use the return inside the mapping.
how will it get the cryptoChartData state get updated ? if its not set?
I meant only the return. You still need to call the this.setState({cryptoChartData: data});
Thank you, it worked perfectly, why was the way I was doing it wrong?

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.