Fetching Data
- Fake back end:
https://jsonplaceholder.typicode.com/
- To send a request to the server, you can use
fetch
function that is implemented in all modern browsers.
axios
library
Axios
- React is a library for building front-end user interfaces, but to create complete apps, we also need a back-end server to handle business logic, data storage, and other functionality
- To send HTTP requests to the backend, we can use
axios
, a popular JavaScript library which makes it easy to send requests
- Install
npm i axios@1.3.4
import axios from "axios";
const [users, setUsers] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((res) => {
setUsers(res.data);
});
}, []);
return (
<>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</>
);
- A promise is an object that holds the eventual result or failure of an asynchronous (long running) operation.