GET Request with Axios
Create a component MyBlog and hook it into the component DidMount lifecycle. Import the Axios at the top and fetch the data with Get request.
Javascript
// Filename - App.js import React from "react" ; import axios from "axios" ; export default class MyList extends React.Component { state = { blogs: [], }; componentDidMount() { axios .get( `https: //jsonplaceholder.typicode.com/posts` ) .then((response) => { const posts = response.data; this .setState({ posts }); }); } render() { return ( <ul> { this .state.posts.map((post) => { post.title; })} </ul> ); } } |
Here we are using axios.get (URL) to get a promise that returns a response object. Returned response is assigned to the post’s object. We can also retrieve other information such as status code etc.
Axios in React: A Guide for Beginners
In React, backend communication is typically achieved using the HTTP protocol. While many developers are familiar with the XML HTTP request interface and Fetch API for making HTTP requests, there’s another powerful library called Axios that simplifies the process further.
Table of Content
- Prerequisites
- Introduction to Axios
- Steps to Create React Application
- Need of Axios in React
- GET Request with Axios
- POST Request with Axios:
- Delete Request With Axios:
- Response Objects in Axios
- Error Object:
- Features of Axios Library
- Shorthand Methods in Axios
- Conclusion
Contact Us