Hello (I am learning React), I am working with an API that returns pictures of random people, however the problem I am having is when I use axios.get I am getting the response from the API, and I can see the results in the console, but when I try to access them it says "Cannot read properties of picture".
The thing I am making is that when the user press the input field it gets an URL of a random picture from the API and the value from that inputText changes to the URL, but it says "Cannot read properties of picture" when clicking on the input, but the API is returning me the data in the console.
Here is what my API returns me.
Here is my code.
class PersonasInsert extends Component {
urlPersonas = "https://randomuser.me/api/?inc=picture";
constructor(props) {
super(props);
this.state = {
peticionImagen: null,
name: "",
last: "",
image: "",
};
}
peticionImagenPersona = async () => {
await axios.get(this.urlPersonas).then(
(response) => {
this.setState({ peticionImagen: response.data.results });
},
(error) => {
console.log(error);
}
);
};
handleChangeImage = async (event) => {
this.peticionImagenPersona();
const peticionImagen = this.state.peticionImagen.picture.large
this.setState({ peticionImagen });
};
render() {
const { peticionImagen } = this.state;
return (
<Wrapper>
<Title>Insertar Persona</Title>
<Label>image: </Label>
<InputText
type="text"
value={peticionImagen}
readOnly
onClick={this.handleChangeImage}
/>
</Wrapper>
);
}
}
export default PersonasInsert;
Thank you in advance.
Does the API return an array of objects or a single object? It looks like an array from the log you posted, you will need to traverse the array through .map or if you want only the first element then do something like this: this.state.peticionImagen[0].picture.large