I tried to create an application from an Random user API in react and I used axios library for HTTP Requests.I created a separate file for base API using axios.create and the file code goes as,
import axios from 'axios'
export default axios.create({
baseURL: `http://jsonplaceholder.typicode.com`,
});
Then I used this in another file to make an GET request and store the data in state on componentdidMount so ill can access the data in UI.
import React from "react";
import API from "../api";
export default class PersonList extends React.Component {
state = {
persons: []
};
componentDidMount() {
API
.get('/').then((data) => {
const persons = data.data;
this.setState({ persons });
console.log(this.state.persons);
});
}
render() {
const { persons } = this.state;
console.log('Stato',persons)
return (
<ul>
{persons.map((person) => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}
}
But it doesn't work ,because the state is not filled up with Users data,so the .map() function is throwing an error.