Joe
Joe

Reputation: 1175

ReactJS - Can't access properties in object from a fetch

I'm doing a fetch to an API and it's returning the data fine, but when I try access the properties, it returns:

Error: Objects are not valid as a React child (found: object with keys {breeds, categories, id, url, width, height}). If you meant to render a collection of children, use an array instead.

myFetch.jsx

import React, {Component} from "react"

class myFetch extends Component {

    state={
        data:[]
    }

    componentDidMount(){
        const url = "xxxxxxxxxxxxxxxxxxxxxxx"
        fetch(url)
        .then(r=>r.json())
        .then(data=>{
            this.setState({data:data})

            // console.log(data)
    })
    .catch(e=>console.log(e))
    }



    render(){

        const {data} = this.state
        console.log(data[0])
        return (<p>{data[0]}</p>)
    }
}

export default myFetch

EDIT

"data" in the state is initialized to an array. Therefore, I should have iterated through the array during the render as {data.map(d => d.url)} and access whichever property I desire as shown below:

render(){

    const {data} = this.state
    console.log(data)
    return (<p>{data.map(d=>d.url)}</p>)
}

Upvotes: 0

Views: 1260

Answers (1)

pahferreira
pahferreira

Reputation: 126

Your data on the state doesn't have any element on 0 index. That's why you getting that undefined error. You can check if it exists before trying to render it.

Something like that:

render() {
const { data } = this.state;
if (data[0]) {
  console.log(data[0]);
  return <p>{data[0].url}</p>;
}
return null;

}

Upvotes: 1

Related Questions