CRUD App with React And JSON-Server
Building a CRUD App is a good start to learn web development.
When you start to learn React (or any other frontend framework), you would eventually end up with one common question. How to perform CRUD functionalities without creating your own backend service?
The answer is below
“Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Created with ❤ for front-end developers who need a quick back-end for prototyping and mocking.” — json-server
The final output of this App will be as below.
In general, however complex your web app maybe, three things are common
a) Backend service — To store and retrieve data. (The role of a backend service is much more including session management, hosting etc. Will stick to only the data retrieval part for this example)
b) Frontend service — To read the data from the backend and add interactions to it. Interactions include the Update/Delete functionality as seen in the example.
c) CSS —For styling. Although styling doesn’t make or break your App, its a good practice to always include it. Without CSS, the example App would look plain old boring 😃. Since it’s a vast subject to learn, the easiest way is to use Bootstrap to quickly get professional looking pages.
Going with the above concepts, let’s dive deeper on how to create this example App and learn the basics of each component along the way.
JSON Server as the Backend for Data retrieval.
We have seen at the start that Backend is one of the three pillars that forms your web app. But there’s a lot of work to do even if we even simply want to create a service for data retrieval.
Setup a local database, create some tables, build a HTTP server , create routes on the Server for different operations, write SQL to manipulate the data in the tables…..and the list goes on.
JSON Server simplifies all of this. Just npm install -g json-server
and you get a readymade Database and a HTTP Server .This package uses a single file db.json
(or any other JSON file), treats the file as a JSON database and also exposes routes on which you canGET, POST, PUT, DELETE
for that db.json
file.
To start your service, all you have to do is open your terminal and runjson-server --watch db.json --port 3000
For this article, I am using the below db.json
file
With this service running, you now have the following routes activated which we can
GET
http://localhost:3002/posts/GET
http://localhost:3002/posts/:idPOST
http://localhost:3002/posts/PUT
http://localhost:3002/posts/:idDELETE
http://localhost:3002/posts/:id
/:id
at the end is to retrieve or manipulate a particular record with that “id”
from the db.json
file.
For example,GET
http://localhost:3002/posts/1 will retrieve the record with the Title “JSON SERVER”
And there you are, with one file and a command, your Backend service is ready. To go even one step further, you can check out Typicode which is the same package hosted on Heroku , so you need not install any local package.
REACT as the Frontend for adding interactions.
With your Backend taken care, its time to use those defined routes into your Frontend framework and add interactions to your App. This essentially creates our “user experience”. This article hopes you already know the basics of React as we will focus more on how to build the Example App with the already established concepts of the framework.
If you are completely new to React, I would highly recommend to go through the Tic Tac Toe game example at https://reactjs.org/. The tutorial is very well explained and will cover all the concepts required for this example.
I have used codesandbox.io for writing all my React code for this example and is currently residing in this sandbox. I would recommend to open the code in another tab which will help walkthrough the code as we move ahead in this article.
So, coming back to React, the overall component tree for our App is as below
CRUD as you’ll know stands for Create, Read, Update and Delete. The next sections will cover these aspects in details
R — Read
In HTTP language, Read is called GET
. We don’t require React to make a GET
request, we use the FETCH API for that. React comes into action when we have to Render the output received from the FETCH API call.
If we inspect the App.js file, we have the below getLists()
function. Now this function does two things
- Uses
Fetch
API toGET
the list of all Posts. ( Routeshttp://localhost:3002/posts
and others are provided by the already running JSON Server) - Alters the
state
of theApp
component (App.js) and populates thealldata
state variable
Once the state
has changed, the Lists
component (Lists.js) renders each record in the JSON output as an individual row with an Update
component (UpdateList.js) and a Delete
component (DeleteList.js) using the alldata
state variable passed in as Props
to the component.
All this happens when the onClick
event is triggered on the “Get Lists” button. This forms our first part of the App, the READ functionality.
C — Create
In HTTP language, Create is POST
. Similar to GET
, POST
and other HTTP actions are performed by the Fetch
API.
We have created a separate Create
Component (CreateList.js) for this functionality. This component renders a HTML <form>
to provide <input>
for entering “Title” and “Author”. The onClick
event handler inside this Component triggers the createList()
function in (App.js) which registers a new record (values taken from the <input>
fields inside the <form>
) in the db.json
file and also resets the state
at the end.
Please refer to the complete listing of the (CreateList.js) to learn more on how to build <form>
elements and manage their elements in React.We have now completed our second functionality of our App. Let’s cover the last two together as they have the same working code with a few differences.
U — Update and D — Delete
Both the update and delete functionalities have a common working.
- Similar to the
Create
Component, theUpdate/Delete
Components have a<form>
with the<inputs>
for “Title” and “Author” - The
onClick
handler in the Update/Delete button fetches the required “Title” and “Author” usingGET
http://localhost:3002/posts/:id - The above fetched values are used to render the
<form>
s<input>
values which can be then updated/deleted.
4. The onClick
handler in the inner Update/Delete button (Line 41 in the UpdateList.js and DeleteList.js) triggers the updateList()
function present in App.js
which uses the Fetch API to make the respective call to modify db.json
The below snippet shows the update function, the delete function will be the same except the DELETE
HTTP action will be made instead of PUT
Takeaways
- JSON Server and Fetch API are the the core of the App and not React.
- React has a very minimal usage in the entire example but it’s important is realised when there are many more complex interactions inside your App.
Summary
CRUD activities are the foundation of any web app. So hope this article has got you excited in learning web development, especially with a frontend framework like React.Happy learning…