Ada banyak jenis request yg ada. Dlm projek ni kita guna 3 jenis:
get
request utk dapatkan datapost
request utk send dataput
request utk update data
Kita akan gunakan axios utk perform request ke server. Cara nak guna agak senang berbanding dgn fetch
function yg dh sedia ada.
Aku baru je install axios dlm projek kita, so kau install dulu dlm laptop kau:
npm install
Cara pakai senang je. Kau kene import beberapa file yg aku dh buat
import instance from "./api/instance";
instance
.post(
"/admin/login", // route yg kita target
{
// body, data yg perlu ada (jika perlu)
email: "email@email.com",
password: "password",
},
{
// header
}
)
.then(res => {
// data yg kita dpt drpd request
console.log(res.data);
})
.catch(err => {
// handle error
console.log(err);
});
Token akan disimpan dlm localStorage
Aku dah buat hook
which is useLocalStorage
utk dptkan/simpan access token. Documentation ada kat repo web.
Contoh:
instance
.get("/api/students", {
headers: { Authorization: `Bearer ${token}` },
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
Contoh: Kat atas tadi
Dapatkan semua data students.
Dapatkan specific students
Contoh:
const id = 1;
instance
.get(`/api/students/${id}`, {
headers: { Authorization: `Bearer ${token}` },
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
Add new record/new students gitu.
Contoh:
instance
.post("/api/students", {
name: 'ali',
matric_no: '0000'
ic_no: '0000'
} {
headers: { Authorization: `Bearer ${token}` },
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
Update wallet ammount
Contoh:
const id = 1;
instance
.put(`/api/students/${id}/wallet`, {
amount: 150
} {
headers: { Authorization: `Bearer ${token}` },
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
Suspend status student
Contoh:
const id = 1;
instance
.put(`/api/students/${id}/suspend`, {
active: false
} {
headers: { Authorization: `Bearer ${token}` },
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
test test