How fetch data with axios in react.
How to use react with vite and axios
npm init @vitejs/app app-name
npm install axios
What can I learn from this tutorial ?
How bootstrap a react app with vite
How to fetch data from componentDidMount()
How to install and use axios
import "./App.css";
import React from "react";
import axios from "axios";
class App extends React.Component {
state = {
todos: [],
error: "",
};
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/todos/")
.then((res) => this.setState({ todos: res.data }))
.catch((err) => this.setState({ error: err }));
}
render() {
const titleList = this.state.todos.map((todo) => (
<li key={todo.id} style={{ listStyleType: "none" }}>
{todo.title}
</li>
));
if (this.state.todos && !this.state.error) {
return (
<div className="App">
<header>
<h1>Users</h1>
</header>
<main style={{ margin: "1rem" }}>
<ul>{titleList}</ul>
</main>
</div>
);
}
if (!this.state.todos && this.state.error) {
return (
<div className="App">
<h2>Error fetching data</h2>
<p>{this.state.error}</p>
</div>
);
}
return (
<div className="App">
<h2>Data is loading</h2>
</div>
);
}
}
export default App;


