Axios GET, PUT, POST and DELETE in NextJs (Complete CRUD)
Set Header with Authorization Bearer token
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;
Some API require bearer to be written as Bearer, so you can do:
axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
Fetch data by id in server-side props
id which we going to show
access_token is bearer authorization token
import React, { useEffect } from "react";
export default function App ({data}) {
const [project_title, SetProjectTitle ] = useState('')
const [about, SetAbout ] = useState('')
useEffect( ()=> {
SetProjectTitle(data.portfolio.project_title)
SetAbout(data.portfolio.about)
}, [] )
axios.defaults.headers.common = {'Authorization': `Bearer ${access_token}`}
return (
<>
{ portfolio &&
portfolio.map((d, index) => {
return(
<div key={index}>
<h3 className="font-size-6 mb-0"> {project_title} </h3>
<p className="font-weight-semibold font-size-5 text-black-2 mb-0"> {about}</p>
</div>
)
})
}
</>
);
};
export async function getServerSideProps(context){
const id= context.params.id
const access_token = session?.user.token
const response = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/portfolio/${id}`, {
method: 'GET',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
});
const data = await response.json();
return {
props: {
data:data,
}
}
}
fetch all post
import React, { useEffect } from "react";
export default function App ({data}) {
const [portfolio, SetPortfolio ] = useState('')
useEffect(() => {
SetPortfolio(data.portfolio)
}, [] )
axios.defaults.headers.common = {'Authorization': `Bearer ${access_token}`}
return (
<>
{ portfolio &&
portfolio.map((d, index) => {
return(
<div key={index}>
<h3 className="font-size-6 mb-0"> {d.project_title} </h3>
<p className="font-weight-semibold font-size-5 text-black-2 mb-0"> {d.about}</p>
</div>
)
})
}
</>
);
};
export async function getServerSideProps(context){
const session = await getSession(context)
const access_token = session?.user.token
const response = await fetch(process.env.NEXT_PUBLIC_BACKEND_URL+'/api/portfolio', {
method: 'GET',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
});
const data = await response.json();
return {
props: {
data:data,
}
}
}
update post by id
first fetch data by id then update
import React, { useEffect } from "react";
export default function App ({data}) {
const [project_title, SetProjectTitle ] = useState('')
const [about, SetAbout ] = useState('')
useEffect( ()=> {
SetProjectTitle(data.portfolio.project_title)
SetAbout(data.portfolio.about)
}, [] )
axios.defaults.headers.common = {'Authorization': `Bearer ${access_token}`}
const formsubmit = async(e) => {
e.preventDefault()
const response = await axios.put(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/portfolio/${id}`, { project_title, about } ).then(function(response){
console.log(response.data)
}).catch(function(error){
const err = error.response.data
console.log(err);
})
}
return (
<>
<form onSubmit={formsubmit} >
<div className="form-group">
<label
htmlFor="namedash"
className="d-block text-black-2 font-size-4 font-weight-semibold mb-4"
>
Project Title
</label>
<input
type="text"
className="form-control h-px-48"
id="namedash"
placeholder="Enter your project title"
value={project_title}
onChange={event => SetProjectTitle(event.target.value) }
/>
</div>
<div className="form-group">
<label
htmlFor="aboutTextarea"
className="d-block text-black-2 font-size-4 font-weight-semibold mb-4"
>
About Project
</label>
<textarea
name="textarea"
id="aboutTextarea"
cols="30"
rows="7"
className="border border-mercury text-gray w-100 pt-4 pl-6"
placeholder="Describe about the project..."
value={about}
onChange={ event => SetAbout(event.target.value) }
></textarea>
</div>
<button
className="btn btn-green btn-h-60 text-white min-width-px-210 rounded-5 text-uppercase">
Update {" "}
</button>
</form>
</>
);
};
export async function getServerSideProps(context){
const id= context.params.id
const access_token = session?.user.token
const response = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/portfolio/${id}`, {
method: 'GET',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
});
const data = await response.json();
return {
props: {
data:data,
}
}
}
Delete post by id and update list real time(without refresh list)
import React, { useEffect } from "react";
import { confirmAlert } from 'react-confirm-alert';
import 'react-confirm-alert/src/react-confirm-alert.css';
import Link from "next/link";
export default function App ({data, id}) {
const [project_title, SetProjectTitle ] = useState('')
const [about, SetAbout ] = useState('')
const [portfolio, SetPortfolio ] = useState('')
useEffect( ()=> {
SetProjectTitle(data.portfolio.project_title)
SetAbout(data.portfolio.about)
SetPortfolio(data.portfolio)
}, [] )
axios.defaults.headers.common = {'Authorization': `Bearer ${access_token}`}
function confirmDelete(portfolioId) {
confirmAlert({
title: 'Delete',
message: 'Are you sure to do this.',
buttons: [
{
label: 'Yes',
onClick: () => {
const res = axios.delete(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/portfolio/${id}`).then(function(response){
var newdata = portfolio.filter( d => d.id !== id )
var filtArr = _.filter(portfolio, function(x) { return x.id !== id; });
SetPortfolio(filtArr)
// toast.success(response.data , {position: toast.POSITION.TOP_CENTER })
}).catch(function(error){
console.log('error')
})
}
},
{
label: 'No',
onClick: () => {
console.log(' not');
}
}
]
});
}
return (
<>
{ portfolio &&
portfolio.map((d, index) => {
return(
<div key={index}>
<h3 className="font-size-6 mb-0"> {project_title} </h3>
<p className="font-weight-semibold font-size-5 text-black-2 mb-0"> {about}</p>
<a style={{color: "red"}} onClick={() => confirmDelete(d.id)} href="#">Delete</a>
<Link href={`/freelancer/edit-portfolio/${d.id}`} >Edit</Link>
</div>
)
})
}
</>
);
};
export async function getServerSideProps(context){
const id= context.params.id
const access_token = session?.user.token
const response = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/portfolio/${id}`, {
method: 'GET',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
});
const data = await response.json();
return {
props: {
data:data,
id:id,
}
}
}
if CORS problems occurs in api end point and ask for 'preflight is invalid (redirect)' or 'redirect is not allowed for a preflight request'
then define form method and pass it to the axios lilke this
const formData = new FormData(); formData.append("_method","post")
and pass this constant formData to axios params