As a newcomer to Javascript and React-Native, I am in the process of developing a simple app that scans book barcodes for their ISBN numbers and matches them with their titles. Despite successfully retrieving the ISBN number, I am encountering an issue when trying to fetch the book title from the Google Books API. The error message "undefined is not an object (evaluating '_this.state.results.items[0].title)" keeps appearing. Can someone assist me in identifying the problem and suggest steps to resolve it? Thank you! Please excuse any errors or shortcomings in my code, as I am still learning and appreciate your guidance.
import React from 'react';
import { Dimensions, StyleSheet, Text, View } from 'react-native';
import { BarCodeScanner } from 'expo';
const { width } = Dimensions.get('window');
export default class App extends React.Component {
constructor(props) {
super(props);
this.state= {
results: {
kind: '',
totalItems: 0,
items: []
}
}
this.fetchData = this.fetchData.bind(this);
}
fetchData(isbn) {
fetch(`https://www.googleapis.com/books/v1/volumes?q=isbn:${encodeURIComponent(isbn)}`)
.then((response)=> response.json())
.then((responseData)=> {
this.setState({results: responseData})
});
}
_handleBarCodeRead = ({ type, data }) => {
var isbn = data;
this.fetchData(isbn)
var title = this.state.results.items[0].volumeInfo.title;
alert(`ISBN: ${isbn}, Title: ${title}`)
}
render() {
return (
<BarCodeScanner
onBarCodeRead={this._handleBarCodeRead}
style={[StyleSheet.absoluteFill, styles.container]}
>
<View style={styles.layerTop} />
<View style={styles.layerCenter}>
<View style={styles.layerLeft} />
<View style={styles.focused} />
<View style={styles.layerRight} />
</View>
<View style={styles.layerBottom} />
</BarCodeScanner>
);
}
}
Edit: After realizing my URL was missing "isbn:", I managed to rectify it and now the alert displays the correct book title matched with the ISBN. However, despite receiving the alert, I continue to encounter the same "undefined is not an object (evaluating '_this.state.results.items[0].title)" message.