A Book Data Access Component
For this activity, we'll set up a 'mock' web api and connect to it with AJAX calls. We'll by using the JSON Server package for the mock server, and we'll be using a library called Axios to make the AJAX calls.
In order to understand what's covered in this activity, you should make sure you understand these topics:
We are going to create a component that we can re-use in other projects that we'll be doing throughout this program.
If you were in my Web II class (Intermediate Web Dev), then you created a UserDataAccess component that did CRUD operations against the browser's localStorage database. The data access component that you create in this activity will be used to do CRUD operations on a remote server, which is how many modern web applications are designed. In class we can have a discussion about storing data on the client vs storing it on the server.
Create a folder named book-data-access.
Then create a file in the folder you just created and name it book-data.json, and paste this code into the file:
{
"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"
}
]
}
This will be the data file that we'll point the JSON server to. Note that the file is an object that contains a books property, which is an array of 'book' objects.
JSON Server
JSON server is an npm package that allows you to create a 'mock' web api (web service). This is a tool for prototyping apps so that you don't have to create the backend web service. All you need to do is create a .json file that models your data, and then you can start the JSON server and point it to your .json file.
Install the JSON Server Package
You may have already installed the JSON Server package. To see if you have alread installed JSON Server, run this command the check the version number:
npx json-server --version
If you need to install the JSON Server package, run this command from the terminal (note that you install the package 'globably' by using the -g option):
npm install json-server -g
Now open a terminal and cd into the book-data-access folder. Then run this command to start the JSON server and point it to the book-data.json file:
npx json-server -w book-data.json -p 8080
Now create a file named book-data-access.js (put it in the book-data-access folder) and put this code in it:
const baseURL = "http://localhost:8080/books/";
export function getAllBooks(){
}
export function getBookById(id){
}
export function insertBook(book){
}
export function updateBook(book){
}
export function deleteBook(id){
}
function errorHandler(err){
console.log("ERROR (in book-data-access):", err.message);
throw err;
}
- This is an ES6 module that exports 5 functions (for CRUD/AJAX calls to an API)
- I'm using 'classic' functions here, but they could just as well be arrow functions
- The errorHandler() function is NOT exported, so it's private.
- We'll use this exact same module in our React sample project.
- But we'll test it now, before we just slap it into another project
- YOU SHOULD ALWAYS TEST YOUR CODE (we'll talk more about this soon)
Create a file in the book-data-access folder called test.html and put this code in it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Testing Book Data Access</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script type="module">
import {getAllBooks, getBookById, insertBook, updateBook, deleteBook} from './book-data-access.js';
window.addEventListener("load", () => {
document.querySelector("[name=btn1]").addEventListener("click", () => {
alert("TODO: GET all books")
});
document.querySelector("[name=btn2]").addEventListener("click", () => {
alert("TODO: GET book by id");
});
document.querySelector("[name=btn3]").addEventListener("click", () => {
alert("TODO: POST book");
});
document.querySelector("[name=btn4]").addEventListener("click", () => {
alert("TODO: PUT book");
});
document.querySelector("[name=btn5]").addEventListener("click", () => {
alert("TODO: DELETE book");
});
});
</script>
</head>
<body>
<input type="button" name="btn1" value="GET All Books">
<br>
<input type="button" name="btn2" value="GET Book By ID">
<br>
<input type="button" name="btn3" value="POST Book">
<br>
<input type="button" name="btn4" value="PUT Book">
<br>
<input type="button" name="btn5" value="DELETE Book">
</body>
</html>
Note the following about this starter code:
- The first SCRIPT element links to the Axios library.
- The type attribute of the second SCRIPT element is set to module. This means that you can use the import statement to import modules (or parts of modules).
- The import statement imports the functions (from our component) that we want to test.
Hopefully, by now all the rest of the starter code makes sense to you. Now watch the video (above) and follow along with the steps in.
Part 2 - Using async and await instead of then() and catch()
This is a follow up video to show you how to use async and await to deal with the Promise objects that are returned by the axios methods.