How to build a react + redux project with DataBase Connectivity.
I am about to share with you how I built a simple application to create data base, api calls, established a middleware and a front end to interact. All this from the scratch using a set of trending technologies.
When I started this project, the first thing which I did was to set up a database on MySql. Now, I will share with you some simple commands to run to set up a database and create a table to hold simple data.
Note; I am limiting this blog to use MacBook setup, there are plenty of tutorials online to achieve the same in Windows machine.
Step 1: Open terminal and type cd /usr/local/mysql/bin , this will take you to the bin folder with MySql (to verify type ls and you should be able to see MySql )
Step 2: Login using root user mysql -u root -p , press enter. It will prompt you to enter the root password.
Step 3: You can jump and create a database as part of root user or you may create a new user and grant the new use all privileges to the new user, login using this new user and create a database. My suggestion will be to go for the second option. So , type GRANT ALL PRIVILEGES ON *.* TO ‘username’@’localhost’ IDENTIFIED BY ‘password’; replace the words username and password with anything you may wish for. Exit the database \q and login using the new username and password.
Step 4: Create database type CREATE DATABASE databasename;
Step 5: To start using the database USE databasename;
Step 6: Create a table inside the database, you may have as many tables as you want but for this simple project happy to use one. CREATE TABLE todos ( task_id smallint unsigned not null auto_increment, task_name varchar(20) not null, constraint pk_example primary key (id) );
Step 7: Insert data into the table INSERT INTO todos ( task_id, task_name ) VALUES (‘1’, ‘Wake up ’ );
Step 8: Now you are almost done with the set up , just to check if the date got inserted into the table, type the select query.
That was a quick database setup, the next thing is to create APIs to talk to the database.
So to create the APIs I used node + express.js . To do this, make sure you have node installed on your machine. After that, run the npm init command, that creates the initial backbone of the project. Use npm install to download all the node modules. I made initial adjustments to the package.json file just to get started.
I have written the express code in the server.js file to just keep things simple.
Since I would not like to retype the entire code here, I would suggest you to go to my gitHub repository and clone the project and check the how the server.js code is written. The url to the git repo will be shared at the end of this blog. with how to run instructions.
After establishing connection to the database please make sure that you are comfortable with writing GET, POST, DELETE, PUT methods in express.js
Here comes the most awaited section of this read. Building the front end using Webpack, React + Redux, Sass ( for styling) . To start with, lets take a quick look at the non-expanded folder structure ;
Since 90% of my code sits inside the src folder, here’s an expanded view of src;
Lets talk about each of these files and folders;
The index.html file contains nothing more than the root div. To simply say, it is the main container where the react virtual DOM is rendered.
The App.js file contains the initial store and which is passed to the component. It also has the ReactDOM.render() method. This is how the code looks;
Here journey.js is the main component , which carries the store forward.
Now before we get into store and action side of the story in Redux here are some things worth mentioning ;
Redux has only one state (but we don’t call it state in redux, we call it store) so every redux app has one main store and that store can be created in the store folder ;
Lets see understand what is happening inside the store.js;
The createStore method is called which is passing the root reducer and the api middleware as its parameters. The rootreducer is a combination of little reducers . But what are reducers ? Every time an action is triggered which causes the state to change to that particular action is mapped a reducer which is listening, it takes as input the changing state and returns an updated state after integrating the changing state . Did that not make any sense, will get back to it again later.!
You can also see a middleware as the second parameter, this is used when any api call is made in redux . Read about Thunk , it wont be covered here.
Let’s understand what are actions. Any event that can trigger a change is an action. Example of action on your application, typing of text, selecting an item from drop down or checkbox, making an API call etc. Any time an action takes place the dispatch method is called passing the action as its parameter i.e, this.props.dispatch(updateText(this.props.text, e.target.value,req)); Inside the action.js the updateText() is defined and every action returns a type and value like this;
Now, the type of Action that the action method returns is absolutely necessary for the reducer to understand which is the action that it needs to update.
Reducer functions are simple; they take as input state and action and returns the updated state. eg;
I had mentioned about combined reducers ; this is needed as par Redux’s policy of maintaining one single state throughout the app.
This code sits at the very bottom of your reducer.js file. It will pack all the reducers under one store.
Now how and where to use this updated store. Anywhere you wish to use any value from the updated store the mapStateToProps() method is called. As the name suggests it maps the state to props like this;
With that anywhere you can display the updated values this.props.getResp;
Also, remember to add the withRouter(connect(mapStateToProps)(Page)). Page is the name of your component.
Calling of APIs in redux is handled by thunk . I have used fetch to make calls to the backend.
To build this project I am using webpack.
Well with this you are done with understanding the basics of any simple react redux app.
Please find the project in gitHub https://github.com/Ray-Coder/myProj
I would highly recommend to set up the database and then run the project to understand how things work. The UI is not highly intuitive .
To play around with the UI ; type todos and select the GET option from the dropdown. Use todo and pass values to the ID and Task field , select POST from the dropdown method.
Hope I was able to through some light on react redux flow.
Please ask question and I also suggest you debug the project.
Happy learning :)