0

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>)
}
10
  • What's your interpretation of that error message? Because it seems very clear to me. Commented Mar 30, 2020 at 19:27
  • maybe it is can be done with { data.length && <p> data[0] </p> } if it is only that at initialstate data has no props... can you copy { consoloe.log(data[0]) } or { // console.log(data)} ? Commented Mar 30, 2020 at 19:29
  • It seems clear to me too, but when I tried accessing the properties during the render, it didn't work. What I did was return the array during the fetch call as "this.setState({data:data[0]})". It works now, but only if I return the data during the fetch. Is there a way to return the data during the render? Commented Mar 30, 2020 at 19:29
  • What do you mean "accessing the properties during the render"? What happened exactly? And was that when data[0] was still undefined? Commented Mar 30, 2020 at 19:32
  • @HagaiHarari I did a console.log(data[0]) and it returns the object, when I try to access the properties, for example: console.log(data[0].url) then I get an error : "TypeError: Cannot read property 'url' of undefined" Commented Mar 30, 2020 at 19:34

1 Answer 1

1

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;

}

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

Comments

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.