React Sample Project - Part 7

Create a file in the project folder called book-data.json and put this code into it:

{
	"books":[
		{
			"id":1,
			"title":"The Sun Also Rises",
			"author":"Ernest Hemmingway"
		},
		{
			"id":2,
			"title":"For Whom the Bells Toll",
			"author":"Ernest Hemmingway"
		},
		{
			"id":3,
			"title":"Harvey Popper",
			"author":"J.K. Rowlings"
		}
	]
}

Create a folder named api in the src folder.

Inside the api folder, create a file named book-data-access.js and put this code into it:

import axios from "axios"; // WE HAVE TO IMPORT AXIOS LIKE THIS!!!!

const baseURL = "http://localhost:8080/books/";

export function getAllBooks(){
	return axios.get(baseURL).then(resp => resp.data).catch(errorHandler);
}

export function getBookById(id){
	return axios.get(baseURL + id).then(resp => resp.data).catch(errorHandler);
}

export function insertBook(book){
	return axios.post(baseURL, book).then(resp => resp.data).catch(errorHandler);
}

export function updateBook(book){
	return axios.put(baseURL + book.id, book).then(resp => resp.data).catch(errorHandler);
}

export function deleteBook(id){
	return axios.delete(baseURL + id).then(resp => resp.data).catch(errorHandler);
}

function errorHandler(err){
    console.log("ERROR (in book-data-access):", err.message);
    throw err;
}