React GET HTTP call using axios library | Functional Component

React itself cannot perform the API calls, so it uses HTTP libraries for the same.
Popular HTTP libraries are: 

Axios & Fetch
AXIOS Vs FETCH
Axios
 - By default works on JSON data.
 - HTTP methods.
 - only one .then method is there.
 - better error handling mechanism.
 

AXIOS
Axios is a promise-based library, so the promise must be handled. So we use `then` to handle the promise if it is fulfilled, and `catch` if it is rejected (aka, I get an error). `Then` is a callback function that automatically has the response object as an argument. That’s great for us because the data we’re retrieving will be inside that response object. 


useEffect runs after the component is rendered. Adding the empty brackets [ ] as an argument is necessary so the code doesn’t run in an infinite loop. This second argument tells useEffect to only render if certain values have changed. We’re essentially telling useEffect to only run on render, because we’re passing it an empty value.


Code Example: Get a todo (object)
import React, { useEffect } from "react";
import axios from "axios";

const HttpGet = () => {
const url = "https://jsonplaceholder.typicode.com/todos/2";
const [todo, setTodo] = React.useState({});

const getTodo = () => {
axios
.get(url)
.then((response) => {
const todoData = response.data;
setTodo(todoData);
})
.catch((error) => console.log(error));
};

useEffect(() => {
getTodo();
}, []);

return (
<div>
{console.log(todo.completed)}
<p>{todo.userId}</p>
<p>{todo.id}</p>
<p>{todo.title}</p>
<p>{todo.completed + ""}</p>
</div>
);
};

export default HttpGet;




Code Example: Get array of todo (array of objects)

HttpGet Component
import React, { useEffect } from "react";
import axios from "axios";
import Todo from "../components/Todo";

const HttpGet = () => {
const url = "https://jsonplaceholder.typicode.com/todos";
const [todos, setTodos] = React.useState([]);

const getAllTodos = () => {
axios
.get(url)
.then((response) => {
const todoData = response.data;
setTodos(todoData);
})
.catch((error) => console.log(error));
};

useEffect(() => {
getAllTodos();
}, []);

const todoCards = todos.map((todo) => {
return <Todo key={todo.id} todo={todo} />;
});

return <div>{todoCards}</div>;
};

export default HttpGet;

Todo Component
import React from "react";

const Todo = ({ todo }) => {
return (
<div style={{ backgroundColor: "grey" }}>
<p>{todo.id}</p>
<p>{todo.userId}</p>
<p>{todo.title}</p>
<p>{todo.completed + ""}</p>
</div>
);
};

export default Todo;

OUTPUT









Comments

Popular posts from this blog

Bootstrap With React

React GET HTTP call using fetch library | Functional Component