Many websites on the interface need REST API in their development. Axios is promise based http client for the browser. Promise here is either rejected or resolve. Javascript provide us async and await to deal with promise. Promise are useful when performing asynchronous tasks. Asynchronous task means , it will not block other things to happen.
How to install axios in react.js
npm install axios
Making Get request in axios
import React from 'react';
import Axios from 'axios'
export default function HomeScreen(){
const [todo,setTodo]=useState([])
//const [id,setId]=useState('')
const navigate=useNavigate()
const Get=async()=>{
const data=await Axios.get("http://localhost:5000/api/get")
console.log(data.data);
setTodo(data.data);
}
useEffect(()=>{
Get();
},[])
render(
<div className='employees-details'>
<table className="table">
<thead className="table-head">
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{todo.map((x,i)=>(
<tr key={i}>
<td>
{x.name} {x.email}
</td>
<td ><button type="button" class="btn btn-secondary" onClick={(e)=>detailsHandler(e,x)}>Details</button>
<button type="button" class="btn btn-warning" onClick={(e)=>editHandler(e,x._id)} >Edit</button>
<button class="btn btn-danger" onClick={(e)=>deleteHandler(e,x._id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
First react and axios is imported so that both can be used in this component.
axios.get(url) where url is the endpoint of API to get a promise which returns response object. Then the result data is shown on the screen using map function.
Making Post request in axios
import { useState } from "react";
import axios from "axios";
import { useNavigate ,Link} from 'react-router-dom';
function CreateEmployee () {
const [employeeInfo, setEmployeeInfo] = useState({ name: "", email: "" });
const navigate=useNavigate();
function handleChange(e) {
setEmployeeInfo((data) => ({ ...data, [e.target.name]: e.target.value }));
}
function handleSubmit(e) {
//e.preventDefault();
axios
.post("http://localhost:5000/api/create", employeeInfo)
.then((res) => {
setEmployeeInfo({ title: "", description: "" });
console.log(res.data.message);
})
.catch((err) => {
console.log("Error couldn't create TODO");
console.log(err.message);
});
}return (
<>
<section className="container">
<Link to='/'>
<button type="button" className="btn btn-primary">
🔙 back
</button></Link>
<section className="todo-data">
<form onSubmit={handleSubmit} className="form-group" noValidate>
<label className="label" htmlFor="title">
Name
</label>
<input
type="text"
name="name"
value={employeeInfo.name}
onChange={handleChange}
className="input"
required
/>
<label className="label" htmlFor="description">
Email
</label>
<input
type="email"
name="email"
value={employeeInfo.email}
onChange={handleChange}
className="input"
required
/>
<button type="submit" className="btn btn-success">
➕ create Employee
</button>
</form>
</section>
</section>
</>
);
};
axios.post(url,data) is used to send the data to the server. url is the endpoint of the API and data is the data which is to be sent to the server.
Making delete request in axios
const deleteHandler = async(e,id) => {
//e.preventDefault()
await Axios.delete(`http://localhost:5000/api/delete-employee/${id}`);
setTodo((data) => {
return data.filter((todo) => todo._id !== id);
});
//console.log(result)
//Get()
};
const editHandler=async(e,id)=>{
console.log(id);
navigate('/update',{state:id})
}
axios.delete(url) is used to delete the data from the server . url is the endpoint of the API in which id of data is passed inside the url to the server delete.
Making put request in axios
import Axios from 'axios';
import React, { useEffect, useState } from 'react';
import {useNavigate} from 'react-router'
import {useLocation} from 'react-router-dom';
const UpdateEmployee=(props)=>{
const navigate=useNavigate()
const [email,setEmail]=useState("");
const [name,setName]=useState("");
const location=useLocation();
//console.log(location.state)
useEffect(()=>{
const get=async()=>{
const result= await Axios.get(`http://localhost:5000/api/edit-employee/${location.state}`);
console.log(result.data);
setName(result.data.name)
setEmail(result.data.email)
}
get()
},[location.state])
const SubmitHandler=async(e)=>{
e.preventDefault()
const result= await Axios.put(`http://localhost:5000/api/update-employee/${location.state}`,{name:name,email:email});
navigate('/')
console.log(result)
}
return (
<>
<div className='data'><h1>Edit Employee Details</h1></div>
<div className='employees-details'>
<form onSubmit={(e)=>SubmitHandler(e)}>
<input type='text' value={name} onChange={(e)=>setName(e.target.value) } ></input>
<input type='email' value={email} onChange={(e)=>setEmail(e.target.value) } ></input>
<div>
<button type='submit' class="edit">Click to edit</button>
</div>
</form>
</div>
</>
)
}
export default UpdateEmployee
axios.put(url,data) which is used to send the data to update in the server. url is the endpoint of the API and data is the information which is to be updated in the server.
This is the main four method that is commonly used in react.js
Are you new to React.js or Just started learning and struggling with react.js project? We have team of react.js developer to help you in react.js project, assignment and for learning react.js at affordable price.
Comentarios