0

I am having an issue with petfinder API and ReactJS. Everything works until I try to access the pets "object/array".

import React, { Component } from 'react';
import { getPets } from '../actions'
import { connect } from 'react-redux'

class Pets extends Component {
  componentDidMount() {
    this.props.getPets()
  }
  render() {
    if (this.props.getPets === null) return null
    const { arrOfPets } = this.props
    const allPets = arrOfPets.petfinder
    console.log(allPets)
    return (
      <div>

      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    arrOfPets: state.pets
  }
}

export default connect(mapStateToProps, { getPets })(Pets)

error-code

It console logs everything fine and as soon as I add .pets to the allPets const it gives me the error can't find pets of undefined.

const allPets = arrOfPets.petfinder.pets

error

General Grievance
  • 4,555
  • 31
  • 31
  • 45
boomer1204
  • 43
  • 6

2 Answers2

0

Don't wrap arrOfPets in curly brackets. Try this:

if (this.props && this.props.petfinder) {
const arrOfPets = this.props
const allPets = arrOfPets.petfinder
}

If you want to use the destructuring syntax, your variable will need to match the object property name.

const { petfinder } = this.props

Javascript (ES6) const with curly braces

Community
  • 1
  • 1
Tim Grant
  • 3,300
  • 4
  • 23
  • 31
  • I guess I don't understand how that would work since petFinder is the first "node" of the api return/promise? this.props.petFinder doesn't exist the state i'm mapping to props is arrOfPets not petfinder? I'm still new so if i'm wrong just lmk but it doesn't work for me it throughs an error. Also in your if statement suggestion I can't access the arrOfPets or allPets when I do it that way – boomer1204 May 09 '17 at 01:14
  • I'm not exactly following your comment. Your code example tests for the existence of this.props.getPets and then assumes the existence of this.props.arrOfPets. I think that's where you are running into trouble. – Tim Grant May 09 '17 at 01:21
  • arrOfPets is the value i'm passing into a prop from the state i'm grabbing from my redux store by running "this.props.getPets". this.props.arrOfPets is giving back the promise data after running through my middleware. The ONLY time i have an issue is when I try and grab .pets from the store. Everything before that runs fine and consoles fine so i'm grabbing the right thing it's the .pets that is messing it up. not sure if it's my code or maybe the api. Look at the first screenshot that is console.log of this.props.arrOfPets.petFinder. You will see pets is a node of that – boomer1204 May 09 '17 at 01:25
  • Like the other poster mentioned, the screenshots are difficult to read. Could you paste the relevant text into the question? – Tim Grant May 09 '17 at 11:09
0

After digging deeper it appears there is an issue with the api itself. Thanks for the help!!!

boomer1204
  • 43
  • 6