0

I am trying to access single elements within an object and I keep getting an error.

Here is my React Component:

import React, { Component } from "react";
import { fetchCoin } from "../redux/actions";
import { connect } from "react-redux";

class ViewCoin extends Component {
  componentDidMount() {
    this.props.fetchCoin(this.props.match.params.symbol);
  }

  render() {
    console.log("Props:", this.props.coin);
    return (
      <div>
        <h2>View Item Page</h2>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    coin: state.coins.coin
  };
};

export default connect(mapStateToProps, { fetchCoin })(ViewCoin);

This code returns the following object:

{
    "BTC": {
        "urls": {
            "website": [
                "https://bitcoin.org/"
            ],
            "twitter": [],
            "reddit": [
                "https://reddit.com/r/bitcoin"
            ],
            "message_board": [
                "https://bitcointalk.org"
            ],
            "announcement": [],
            "chat": [],
            "explorer": [
                "https://blockchain.info/",
                "https://live.blockcypher.com/btc/",
                "https://blockchair.com/bitcoin/blocks"
            ],
            "source_code": [
                "https://github.com/bitcoin/"
            ]
        },
        "logo": "https://s2.coinmarketcap.com/static/img/coins/64x64/1.png",
        "id": 1,
        "name": "Bitcoin",
        "symbol": "BTC",
        "slug": "bitcoin",
        "date_added": "2013-04-28T00:00:00.000Z",
        "tags": [
            "mineable"
        ],
        "category": "coin"
    }
}

When trying to access the coin name, for example, I issue the command:

console.log(this.props.coin.BTC.name);

I get the error: Cannot read property 'BTC' of undefined

I tested accessing values in this object outside of React and I am able to access the different values. How would one access a nested object like this using React.

Thanks in advance.

1
  • looks fine, but you need a constructor. constructor(props){ super(props) } Commented Nov 21, 2018 at 1:55

1 Answer 1

1

What's likely happening is the first time that component renders coin is undefined. When the action returns, the props are updated, the component re-renders and coin is logged out.

Do something like this in render and it should work:

this.props.coin && console.log('coin name:', this.props.coin.BTC.name)
Sign up to request clarification or add additional context in comments.

1 Comment

glad to hear it!

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.