Last week we left off on the following code:
onSearchSubmit(term){axios.get('https://api.unsplash.com/search/photos', {params: { query: term },headers: {Authorization: 'Client-ID zIN-FurWn1HMVuVrNA08M5IPNbNcLT6S3fuSXZPxgvM'}}).then( (resp) => {console.log(resp.data.results);});}
If we go to the page and search for “Cars” a request will be made to that API we talk about before and let's see that response in the network tab of the developer tool.
We have some information coming from the API. Let's open the result tab and we will have an array of elements.
Let's now take that information using the then() method to catch that returned promise from the API.
onSearchSubmit(term){axios.get('https://api.unsplash.com/search/photos', {params: { query: term },headers: {Authorization: 'Client-ID zIN-FurWn1HMVuVrNA08M5IPNbNcLT6S3fuSXZPxgvM'}}).then( (resp) => {console.log(resp.data.results);});}
Now, this console.log() will show the information we are receiving from the API and the next step is going to be showing that on the page.
So let's initialize the state property inside the application component to be able to have access to the state and show the information on the page.
state = {images: []}
We are initializing the state as an object and passing an empty array to be able to use the appropriate method since we are receiving an array from the API.
Let's refactor the code for onSearchSubmit to avoid errors when calling this.setState by making the function an arrow key version.
onSearchSubmit = async (term) => {const resp = await axios.get('https://api.unsplash.com/search/photos', {params: { query: term },headers: {Authorization: 'Client-ID zIN-FurWn1HMVuVrNA08M5IPNbNcLT6S3fuSXZPxgvM'}});this.setState({images: resp.data.results})}
I did refactor how I'm handing the promise with async and await because the code is easier. to learn more visit https://axios-http.com/docs/intro for more details.
I'm adding this: Found: {this.state.images.length}
on the render() method to make sure I still have access to the information from the API.
Let's pause here and I will see you next week for part 3 where we're are going to build a different component to render the list of images.