Reputation: 11
I am developing a React application that searches and brings up pictures and videos of the topic I searched using Pixabay API. However, I am encountering "Cannot read property 'id' of undefined" when I try to call id of the API call that I fetched. What can I do to fix this error?
API Call: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {id: 801826, pageURL: "https://pixabay.com/photos/pug-dog-pet-animal-puppy-cute-801826/", type: "photo", tags: "pug, dog, pet", previewURL: "https://cdn.pixabay.com/photo/2015/06/08/15/02/pug-801826_150.jpg", …} ...
App.js
import './App.css';
import React from 'react';
import Board from './board/board';
import ImageSearch from './imageSearch/imageSearch'
const API_KEY = "19435337-59a77b980b37e8c813d079adb"
class App extends React.Component {
state = {
images: []
}
handleGetRequest = async (event) => {
event.preventDefault();
const searchValue = event.target.elements.searchValue.value;
const URL = `https://pixabay.com/api/?key=${API_KEY}&q=${searchValue}&image_type=photo&per_page=7`
const request = await fetch(URL);
const response = await request.json();
this.setState({ images : response.hits });
console.log (this.state.images)
}
render() {
return (
<div>
<ImageSearch handleGetRequest={this.handleGetRequest}/>
<Board image={this.state.images[0]} />
</div>
)
}
}
export default App;
Board.js
import './board.css';
import React from 'react';
const Board = (image) => {
return (
<div>
<div key={image.image.id}>
<input type="image" className="board__image" src={image.image.largeImageURL} alt={image.image.tags}></input>
</div>
</div>
)
}
export default Board;
Upvotes: 0
Views: 61
Reputation: 5763
The result does not exist until the API call is completed. You need to check if it exists before rendering the markup in your Board
component:
const Board = (image) => {
return (
<>
{ image && <div>
<div key={image.image.id}>
<input type="image" className="board__image" src={image.image.largeImageURL} alt={image.image.tags}></input>
</div>
</div> }
</>
)
}
Or any other solution that ensures the image exists should work.
Upvotes: 1