React- Requesting an image from an API

Hello everyone, I am trying to build an app in React that shows a small card with some sample info and a photo.
The info is all set, using the placeholder JSON, However I am having trouble doing the same with images.
I am using https://thecatapi.com/ I have my own api key, unfortunately i don’t have much experience with apis.
I copied my api request for the json info and tried that:

componentDidMount() {
fetch('https://api.thecatapi.com/v1/images/search')
.then(Response =>Response.json())
.then(pic => this.setState({kittens: pic}))
}

Since that didn’t work I need some help.
I am guessing that I would get the images and then put them into an array, but I don’t know how to do that.
Please help, thank you in advance.

If you look at the response you’ll see that it consists of an array of objects that have url key.
So you code should work - after fetch you’ll have in this.state.kittens an array with objects. Now you need to loop over it and use it in you code (e.g. use url key as src for the <image> tag).

1 Like

Thanks for responding. I have a few follow up questions if you don’t mind.
My whole application won’t compile because of TypeError: Cannot read property 'kittens' of undefined
So I can’t see anything that’s being returned. How exactly would I write a proper api fetch statement so that it will return an array of objects?
From there I should be able to figure it out myself.

Without seeing the rest of your code it would be just guessing.
Use codesandbox.io to post your code.

The first render won’t have the data on your obj. So, it would be good to have a spinner/loading if condition before rendering, then, with the data retrived from the webserver you will be able so access it.

Hi man, this is the solution that i came up with, maybe it will help:

class App extends Component {

constructor() {

super();

this.state = {

  catei: [],

};

}

componentDidMount() {

fetch("https://jsonplaceholder.typicode.com/users")

  .then((repsonse) => repsonse.json())

  .then((users) => {

    const fetchArray = [];

    users.forEach(() => {

      fetchArray.push(fetch("https://api.thecatapi.com/v1/images/search"));

    });

    Promise.all(fetchArray)

      .then((res) => {

        const jsonArray = [];

        res.forEach((r) => {

          jsonArray.push(r.json());

        });

        return Promise.all(jsonArray);

      })

      .then((imgs) => {

        console.log(imgs);

        users.map((user, index) => {

          user.url = imgs[index][0].url;

          return user;

        });

        this.setState({ catei: users });

      });

  });

}