Transposing and aggregating Oracle column data

I have the following data

I have the following data

Base          End
RMSA          Item 1
RMSA          Item 2
RMSA          Item 3
RMSB          Item 1
RMSB          Item 2
RMSC          Item 4

I want to convert it to the following format

    Key           Products
    RMSA;RMSB     Item 1, Item 2
    RMSA          Item 3
    RMSC          Item 4

Basically, those with similar results should be grouped into 1 line. However, I can't seem to get it to work using listagg, etc since I'm grouping on two columns.

Is there any way to do this with a direct Oracle query?

Build a REST API with Express and Sequelize

Build a REST API with Express and Sequelize

In this tutorial all steps for building a REST API with Express and Sequelize.

In this tutorial all steps for building a REST API with Express and Sequelize.

When I started learning Node I made the same mistake as most bootcamp graduates these days. I went straight for NoSQL databases without even considering SQL as an option and I had no idea what I had missed out on until when I was recently exposed to Ruby on Rails and SQL. I learned the difference between the two type of databases and managed to love both of them, equally. Because of my newly found knowledge I decided to write a walkthrough on how to build a REST API using Express and Sequelize.

Let’s start by installing the npm packages that we will use:

npm init
npm install express sequelize sqlite3 body-parser --save
npm install sequelize-cli -g

sequelize init

The command “sequelize init” will create the backbone of our database architecture and will allow us to easily connect to our database to insert/retrieve/delete records. Once that command is completed you will see a couple of extra folders and files in your app and your folder structure should look something like this:

|- express-sequelize
|-- config
|--- config.json
|-- migrations
|-- models
|--- index.js
|-- node_modules
|-- seeders
|-- package.json
|-- package-lock.json

The planned database models and the relationships between them will look something like this:

For this tutorial I will use SQLite3 for the sake of simplicity; in order to use that with Sequelize we have to go into our config/config.json and replace the content of the file with the following:

{
    "development": {
    "dialect": "sqlite",
    "storage": "./database.sqlite3"
  },
    "test": {
    "dialect": "sqlite",
    "storage": ":memory"
  },
    "production": {
    "dialect": "sqlite",
    "storage": "./database.sqlite3"
  }
}

Now that our environment is all set up, it’s time to create the models for our database. Sequelize-CLI allows us to create models on the fly with no effort; we simply have to write the name of the model and the name of the columns in the database that will belong to the current model and the type of data that we will store. Just like this:

sequelize model:create --name Physician --attributes name:string
sequelize model:create --name Patient --attributes name:string
sequelize model:create --name Appointment --attributes physicianId:integer,patientId:integer

After we’re done with this, you’ll see that we have 3 new files inside our *models *folder. All we have to do now is to commit these changes to the database by migrating the changes with the following command:

sequelize db:migrate

This means that our models are created in the database (but, we still have to create the associations between them). We’ll have 2 main models: Physician and Patient. They will be connected by a join table: Appointment. A Physician can have many Patients and vice versa through an Appointment. Let’s start with the Physician. All we have to do is define the association inside the “associate’’ function. The way we do this is on line 11. We select the current model and use the belongsToMany() function that will receive the model we want to connect it to and the optional arguments. In this case we have to include our join table Appointment.

"use strict";
module.exports = (sequelize, DataTypes) => {
  const Physician = sequelize.define(
    "Physician",
    {
      name: DataTypes.STRING
    },
    {}
  );
  Physician.associate = function(models) {
    Physician.belongsToMany(models.Patient, { through: "Appointment", foreignKey: "physicianId" });
  };
  return Physician;
};

We have to do the same with our Patient model:

"use strict";
module.exports = (sequelize, DataTypes) => {
  const Patient = sequelize.define(
    "Patient",
    {
      name: DataTypes.STRING
    },
    {}
  );
  Patient.associate = function(models) {
    Patient.belongsToMany(models.Physician, { through: "Appointment", foreignKey: "patientId" });
  };
  return Patient;
};

And now it’s time to connect these two models with our join model by defining a relationship where Appointment belongs to a Patient and a Physician.

"use strict";
module.exports = (sequelize, DataTypes) => {
  const Appointment = sequelize.define(
    "Appointment",
    {
      physicianId: DataTypes.INTEGER,
      patientId: DataTypes.INTEGER
    },
    {}
  );
  Appointment.associate = function(models) {
    Appointment.belongsTo(models.Physician);
    Appointment.belongsTo(models.Patient);
  };
  return Appointment;
};

This means that our database is ready. It’s time to get started with the Node server. Nothing complicated, just a simple Express server. First of all let’s create a file called server.js and let’s paste this code inside.

const express = require("express");
const bodyparser = require("body-parser");
const port = process.env.PORT || 5000;

const app = express();

app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

require("./routes/appointmentRoutes")(app);
require("./routes/physicianRoutes")(app);
require("./routes/patientRoutes")(app);

app.listen(port, () => console.log(`Server started on ${port}`));

All that is left is to define the routes where our server will receive requests. For this I will create 3 files inside a folder named “routes”, one file for each model. Each file will have the following routes included:

'GET'    /name
'GET'    /name/:id
'POST'   /name
'PUT'    /name/:id
'DELETE' /name/:id 

In these files we’ll import our models from the database that we’ll use and Sequelize will allow us to call methods on these models that execute specific queries in the database. The content of your files will be almost identical, but with different model names.

This is what “physicianRoutes.js” will look like:

const Physician = require("../models").Physician;
const Patient = require("../models").Patient;

module.exports = function(router) {
  router.get("/physicians", (req, res) => {
    Physician.findAll({
      include: [Patient]
    })
      .then(physicians => {
        res.json(physicians);
      })
      .catch(err => res.json(err));
  });

  router.get("/physicians/:id", (req, res) => {
    Physician.findAll({
      where: { id: req.params.id }
    })
      .then(physician => {
        res.json(physician[0]);
      })
      .catch(err => res.json(err));
  });

  router.post("/physicians", (req, res) => {
    Physician.create({
      name: req.body.name
    })
      .then(res => {
        res.json(res);
      })
      .catch(err => res.json(err));
  });

  router.put("/physicians/:id", (req, res) => {
    Physician.update({ name: req.body.name }, { where: { id: req.params.id } })
      .then(updatedPhysician => {
        res.json(updatedPhysician);
      })
      .catch(err => res.json(err));
  });

  router.delete("/physicians/:id", (req, res) => {
    Physician.destroy({
      where: { id: req.params.id }
    })
      .then(physician => {
        res.json(physician);
      })
      .catch(err => res.json(err));
  });
};

If you compare it to “patientRoutes.js”, the only main difference you will see is the model names.

const Physician = require("../models").Physician;
const Patient = require("../models").Patient;

module.exports = function(router) {
  router.get("/patients", (req, res) => {
    Patient.findAll({
      include: [Physician]
    })
      .then(patients => {
        res.json(patients);
      })
      .catch(err => res.json(err));
  });

  router.get("/patients/:id", (req, res) => {
    Patient.findAll({
      where: { id: req.params.id }
    })
      .then(patient => {
        res.json(patient[0]);
      })
      .catch(err => res.json(err));
  });

  router.post("/patients", (req, res) => {
    Patient.create({
      name: req.body.name
    })
      .then(res => {
        res.json(res);
      })
      .catch(err => res.json(err));
  });

  router.put("/patients/:id", (req, res) => {
    Patient.update({ name: req.body.name }, { where: { id: req.params.id } })
      .then(updatedPatient => {
        res.json(updatedPatient);
      })
      .catch(err => res.json(err));
  });

  router.delete("/patients/:id", (req, res) => {
    Patient.destroy({
      where: { id: req.params.id }
    })
      .then(patient => {
        res.json(patient);
      })
      .catch(err => res.json(err));
  });
};

And “appointmentRoutes.js”:

const Appointment = require("../models").Appointment;
const Physician = require("../models").Physician;
const Patient = require("../models").Patient;

module.exports = function(router) {
  router.get("/appointments", (req, res) => {
    Appointment.findAll({
      include: [Physician, Patient]
    }).then(appointments => {
      res.json(appointments);
    });
  });

  router.get("/appointments/:id", (req, res) => {
    Appointment.findAll({
      where: { id: req.params.id },
      include: [Physician, Patient]
    }).then(appointment => {
      res.json(appointment[0]);
    });
  });

  router.post("/appointments", (req, res) => {
    Appointment.create({
      physicianId: req.body.physicianId,
      patientId: req.body.patientId
    })
      .then(appointments => {
        res.json(appointments);
      })
      .catch(err => res.json(err));
  });

  router.put("/appointments/:id", (req, res) => {
    Appointment.update(
      { physicianId: req.body.physicianId, patientId: req.body.patientId },
      { where: { id: req.params.id } }
    )
      .then(updatedAppointment => {
        res.json(updatedAppointment);
      })
      .catch(err => console.log(err));
  });

  router.delete("/appointments/:id", (req, res) => {
    Appointment.destroy({
      where: { id: req.params.id }
    }).then(appointment => {
      res.json(appointment);
    });
  });
};

These three files will help us to carry out the basic CRUD functionality in our app. Of course we can create more endpoints where we can describe what to do in specific cases or what to return.

This is all for now, if you start up your server and populate your database you can Create, Read, Update and Delete your records.

Spring Boot + JPA + Hibernate + Oracle

Spring Boot + JPA + Hibernate + Oracle

In this tutorial, we will learn how to create a Spring Boot application that communicates with an Oracle data source through Hibernate.

In this tutorial, we will learn how to create a Spring Boot application that communicates with an Oracle data source through Hibernate.

Prerequisites
  • Eclipse IDE (neon release)
  • Maven 4
  • Java 1.8
Create a Maven Project

Open Eclipse, then create a new Maven project and name it SpringBootHibernate.

At the end of this tutorial, we’ll get the following project structure:

pom.xml

Configure Spring Boot inside your pom.xml by adding the following parent dependency:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.RELEASE</version>
</parent>

Then add a spring-boot-starter dependency in order to run the application as a standalone JAR application:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

Now in order to make use of Spring Data JPA and Hibernate, we need to just add spring-boot-starter-data-jpa as a dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

As soon as we include Spring Boot Starter JPA in our project, we get the following features from a wide variety of dependencies:

  • Eclipse IDE (neon release)
  • Maven 4
  • Java 1.8

This is the whole pom.xml for reference:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.programmer.gate</groupId>
  <artifactId>SpringBootHibernate</artifactId>
  <packaging>jar</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBootHibernate</name>

  <properties>
       <maven.compiler.source>1.8</maven.compiler.source>
       <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>

  <dependencies>

      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

  </dependencies>

  <build>
      <plugins>
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
      </plugins>
  </build>

</project>

Add the Oracle Driver to the Classpath

In this tutorial, we’re going to override the default in-memory database provided by Spring Boot and use our own Oracle database.

For this purpose, we add “oracle-ojdbc6-11.2.0.3.jar” under WEB-INF/lib and define it in our classpath.

application.properties

Configure the Oracle data source and Hibernate in application.properties:

# create and drop tables and sequences, loads import.sql
spring.jpa.hibernate.ddl-auto=create-drop

# Oracle settings
spring.datasource.url=jdbc:oracle:thin:@localhost:1522:orcl
spring.datasource.username=HIBERNATE_TEST
spring.datasource.password=HIBERNATE_TEST
spring.datasource.driver.class=oracle.jdbc.driver.OracleDriver

# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug

Entities

Our entities represent a player and a team with a one-to-many relationship. Each team could have many players, whereas a player could only play with a single team at a time.

So we create our entities under the com.programmer.gate.model package:

Player.java:

package com.programmer.gate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;

@Entity
public class Player {

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "player_Sequence")
    @SequenceGenerator(name = "player_Sequence", sequenceName = "PLAYER_SEQ")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "num")
    private int num;

    @Column(name = "position")
    private String position;

    @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "team_id", nullable = false)
        private Team team;

    public Player() {
    }
        // getters/setters
}

Team.java:

package com.programmer.gate.model;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;

@Entity
public class Team {

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "team_Sequence")
    @SequenceGenerator(name = "team_Sequence", sequenceName = "TEAM_SEQ")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToMany(cascade = CascadeType.ALL,
            fetch = FetchType.EAGER,
            mappedBy = "team")
    private List<Player> players;

    public Team() {
    }

        // getters/setters
}

Since we set spring.jpa.hibernate.ddl-auto=create-drop inside application.properties, our application will automatically create Player and Team entities in our database, along with their sequences and constraints.

Our application would also look for import.sql in the classpath and execute it, if found.

In our example, we define import.sql under src/main/resources in order to fill our tables with static data:

insert into Team (id,name) values(1,'Barcelona');

insert into Player (id, team_id, name, num, position) values(1,1,'Lionel Messi', 10, 'Forward');
insert into Player (id, team_id, name, num, position) values(2,1,'Andreas Inniesta', 8, 'Midfielder');
insert into Player (id, team_id, name, num, position) values(3,1,'Pique', 3, 'Defender');

Repositories

We define our repositories’ interfaces under com.programmer.gate.repository. Each repository extends Spring CrudRepository, which provides a default implementation for the basic find, save,and delete methods — so we don’t care about defining implementation classes for them.

PlayerRepository:

package com.programmer.gate.repository;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.programmer.gate.model.Player;

@Repository
public interface PlayerRepository extends CrudRepository<Player, Long> {

    List<Player> findByTeamId(long teamId);
}

TeamRepository:

package com.programmer.gate.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.programmer.gate.model.Team;

@Repository
public interface TeamRepository extends CrudRepository<Team, Long> {

    Team findByPlayers(long playerId);
}

Service

Now we define our service class, which holds the business logic of our application. Our service exposes two methods: getAllTeamPlayers() and addBarcelonaPlayer() ( just rename it to your favorite club if you don’t like Barcelona!). Our service layer communicates directly with the repository layer.

SoccerService.java:

package com.programmer.gate.service;

import java.util.List;

public interface SoccerService {
    public List<String> getAllTeamPlayers(long teamId);
    public void addBarcelonaPlayer(String name, String position, int number);
}

SoccerServiceImpl:

package com.programmer.gate.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.programmer.gate.model.Player;
import com.programmer.gate.model.Team;
import com.programmer.gate.repository.PlayerRepository;
import com.programmer.gate.repository.TeamRepository;

@Service
public class SoccerServiceImpl implements SoccerService {

    @Autowired
    private PlayerRepository playerRepository;
    @Autowired
    private TeamRepository teamRepository;

    public List<String> getAllTeamPlayers(long teamId) {
        List<String> result = new ArrayList<String>();
        List<Player> players = playerRepository.findByTeamId(teamId);
        for (Player player : players) {
            result.add(player.getName());
        }

        return result;
    }

    public void addBarcelonaPlayer(String name, String position, int number) {

        Team barcelona = teamRepository.findOne(1l);

        Player newPlayer = new Player();
        newPlayer.setName(name);
        newPlayer.setPosition(position);
        newPlayer.setNum(number);
        newPlayer.setTeam(barcelona);
        playerRepository.save(newPlayer);
    }
}

Application.java

The final step is to create the Spring Boot initializer. This is the entry point of our application. We define Application.javaunder com.programmer.gate:

package com.programmer.gate;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.programmer.gate.service.SoccerService;

@SpringBootApplication
public class Application implements CommandLineRunner{

    @Autowired
    SoccerService soccerService;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... arg0) throws Exception {

        soccerService.addBarcelonaPlayer("Xavi Hernandez", "Midfielder", 6);

        List<String> players = soccerService.getAllTeamPlayers(1);
        for(String player : players)
        {
            System.out.println("Introducing Barca player => " + player);
        }
    }
}

P.S.: It’s worth mentioning that the Spring Boot application automatically reads and creates entities, repositories, and services defined in the same package or in a sub-package relative to where you have your initializer class. So if we define Application.java under a different package, then we need to explicitly specify the package of the model, repository, and service.

Output:

When running the application as a standard Java app, we get the following output in the console:

2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create sequence player_seq start with 1 increment by 1
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create sequence team_seq start with 1 increment by 1
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create table player (id number(19,0) not null, name varchar2(255 char), num number(10,0), position varchar2(255 char), team_id number(19,0) not null, primary key (id))
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create table team (id number(19,0) not null, name varchar2(255 char), primary key (id))
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - alter table player add constraint FKdvd6ljes11r44igawmpm1mc5s foreign key (team_id) references team
2018-04-13 14:54:47 INFO  o.h.tool.hbm2ddl.SchemaExport - HHH000476: Executing import script '/import.sql'
2018-04-13 14:54:47 INFO  o.h.tool.hbm2ddl.SchemaExport - HHH000230: Schema export complete
2018-04-13 14:54:47 INFO  o.s.o.j.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-04-13 14:54:48 INFO  o.s.j.e.a.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - select team0_.id as id1_1_0_, team0_.name as name2_1_0_, players1_.team_id as team_id5_0_1_, players1_.id as id1_0_1_, players1_.id as id1_0_2_, players1_.name as name2_0_2_, players1_.num as num3_0_2_, players1_.position as position4_0_2_, players1_.team_id as team_id5_0_2_ from team team0_, player players1_ where team0_.id=players1_.team_id(+) and team0_.id=?
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - select player_seq.nextval from dual
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - insert into player (name, num, position, team_id, id) values (?, ?, ?, ?, ?)
2018-04-13 14:54:48 INFO  o.h.h.i.QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - select player0_.id as id1_0_, player0_.name as name2_0_, player0_.num as num3_0_, player0_.position as position4_0_, player0_.team_id as team_id5_0_ from player player0_, team team1_ where player0_.team_id=team1_.id(+) and team1_.id=?

Introducing Barca player => Lionel Messi
Introducing Barca player => Andreas Inniesta
Introducing Barca player => Pique
Introducing Barca player => Xavi Hernandez

2018-04-13 14:54:49 INFO  com.programmer.gate.Application - Started Application in 4.213 seconds (JVM running for 4.555)

Source code

You can download the source code from this repository: spring-boot-jpa-hibernate.

React Native Tutorial: SQLite Offline Android/iOS Mobile App

React Native Tutorial: SQLite Offline Android/iOS Mobile App

React Native Tutorial: SQLite Offline Android/iOS Mobile App

Table of Contents:
  • Install React App Creator and Create App
  • Add Navigation Header and required Screen
  • Install and Configure React Native SQLite Storage
  • Show List of Product
  • Show Product Details and Delete Product
  • Add Product
  • Edit Product
  • Run and Test React Native and SQLite Offline Mobile App

The following tools, frameworks, and modules are required for this tutorial:

  • Install React App Creator and Create App
  • Add Navigation Header and required Screen
  • Install and Configure React Native SQLite Storage
  • Show List of Product
  • Show Product Details and Delete Product
  • Add Product
  • Edit Product
  • Run and Test React Native and SQLite Offline Mobile App

Before start to the main steps, make sure that you have installed Node.js and can run npm in the terminal or command line. To check the existing or installed Node.js environment open the terminal/command line then type this command.

node -v
v10.15.1
npm -v
6.8.0
yarn -v
1.10.1

1. Install React App Creator and Create App

The Create React Native App is a tool for creating a React Native App. To install it, type this command in your App projects folder.

sudo npm install -g react-native-cli

Then create a React Native App using this command.

react-native init reactOffline

That command will create a React Native app then install all required modules. The app or project folder will contain these folders and files.

Next, go to the newly created React App folder.

cd reactSqlite

To run on iOS device or simulator run this command.

react-native run-ios

The simulator will open along with the new terminal window. Go to the project folder from the new terminal window then run this command.

react-native start

Right after iOS build success and React Native started, you will see this view in the iOS Simulator.

To run on Android device or simulator, make sure ADB detected the device.

adb devices
List of devices attached
J8AXGF0194047T6&nbsp;&nbsp; &nbsp;device

Next, type this command to run on the Android device or simulator.

react-native run-android

It will open the new terminal windows. Just go to the project folder then type this command.

react-native start

You will see this app in your Android device.

Sometimes, if running React Native app faster than starting React-Native Javascript bundler you see this red-screen of error.

No bundle URL present.

Make sure you’re running a packager server or have included a .jsbundle file in your application bundle.

RCTFatal
__28-[RCTCxxBridge handleError:]_block_invoke
_dispatch_call_block_and_release
_dispatch_client_callout
_dispatch_main_queue_callback_4CF
__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
__CFRunLoopRun
CFRunLoopRunSpecific
GSEventRunModal
UIApplicationMain
main
start
0x0

Don’t worry, just start the Metro Bundler in the newly opened terminal window after you go to the project folder. After Metro Bundler started completely, refresh the React Native app on your device or simulator. In iOS Simulator you will see this error after refresh.

Attempting to reload bridge before it's valid: <RCTCxxBridge: 0x7ff34bc00510>. Try restarting the development server if connected.

-[RCTCxxBridge reload]
&nbsp; &nbsp; RCTCxxBridge.mm:986
-[RCTRedBox reloadFromRedBoxWindow:]
-[RCTRedBoxWindow reload]
-[UIApplication sendAction:to:from:forEvent:]
-[UIControl sendAction:to:forEvent:]
-[UIControl _sendActionsForEvents:withEvent:]
-[UIControl touchesEnded:withEvent:]
-[UIWindow _sendTouchesForEvent:]
-[UIWindow sendEvent:]
-[UIApplication sendEvent:]
__dispatchPreprocessedEventFromEventQueue
__handleEventQueueInternal
__handleEventQueueInternal
__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
__CFRunLoopDoSources0
__CFRunLoopRun
CFRunLoopRunSpecific
GSEventRunModal
UIApplicationMain
main
start
0x0

Just reload again the React Native app, you will get your React Native app running.

2. Add Navigation Header and required Screen

Above generated React Native App just show blank app with plain text. Now, we will show you how to add the Navigation Header and Home Screen for your app. So, it will look like the Native App. In the terminal or command line, type this command to install React Navigation module and don’t forget to stop the running Metro Bundler before installing the modules.

yarn add react-navigation --save
yarn add react-native-gesture-handler --save
react-native link react-native-gesture-handler

Next, create a folder for components and components files in the root of the app folder.

mkdir components
touch components/ProductScreen.js
touch components/ProductDetailsScreen.js
touch components/ProductAddScreen.js
touch components/ProductEditScreen.js

Open and edit components/ProductScreen.js then add this React codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

export default class ProductScreen extends Component {
&nbsp; static navigationOptions = {
&nbsp; &nbsp; title: 'Product List',
&nbsp; };
&nbsp; render() {
&nbsp; &nbsp; return (
&nbsp; &nbsp; &nbsp; <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
&nbsp; &nbsp; &nbsp; &nbsp; <Text>Product List</Text>
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Details"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.navigate('ProductDetails')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Add Product"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.navigate('AddProduct')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Edit Product"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.navigate('EditProduct')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; );
&nbsp; }
}

Open and edit components/ProductDetailsScreen.js then add this React codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

export default class ProductDetailsScreen extends Component {
&nbsp; static navigationOptions = {
&nbsp; &nbsp; title: 'Product Details',
&nbsp; };
&nbsp; render() {
&nbsp; &nbsp; return (
&nbsp; &nbsp; &nbsp; <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
&nbsp; &nbsp; &nbsp; &nbsp; <Text>Product Details</Text>
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Details... again"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.push('ProductDetails')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Home"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.navigate('Product')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go back"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.goBack()}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; );
&nbsp; }
}

Open and edit components/ProductAddScreen.js then add this React codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

export default class ProductAddScreen extends Component {
&nbsp; static navigationOptions = {
&nbsp; &nbsp; title: 'Add Product',
&nbsp; };
&nbsp; render() {
&nbsp; &nbsp; return (
&nbsp; &nbsp; &nbsp; <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
&nbsp; &nbsp; &nbsp; &nbsp; <Text>Add Product</Text>
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Add Product... again"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.push('AddProduct')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Home"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.navigate('Product')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go back"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.goBack()}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; );
&nbsp; }
}

Open and edit components/ProductEditScreen.js then add this React codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

export default class ProductEditScreen extends Component {
&nbsp; static navigationOptions = {
&nbsp; &nbsp; title: 'Edit Product',
&nbsp; };
&nbsp; render() {
&nbsp; &nbsp; return (
&nbsp; &nbsp; &nbsp; <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
&nbsp; &nbsp; &nbsp; &nbsp; <Text>Add Product</Text>
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Edit Product... again"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.push('EditProduct')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go to Home"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.navigate('Product')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Go back"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.props.navigation.goBack()}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; );
&nbsp; }
}

Next, open and edit App.js then add replace all codes with this.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createAppContainer, createStackNavigator } from 'react-navigation';
import ProductScreen from './components/ProductScreen';
import ProductDetailsScreen from './components/ProductDetailsScreen';
import ProductAddScreen from './components/ProductAddScreen';
import ProductEditScreen from './components/ProductEditScreen';

const RootStack = createStackNavigator(
&nbsp; {
&nbsp; &nbsp; Product: ProductScreen,
&nbsp; &nbsp; ProductDetails: ProductDetailsScreen,
&nbsp; &nbsp; AddProduct: ProductAddScreen,
&nbsp; &nbsp; EditProduct: ProductEditScreen,
&nbsp; },
&nbsp; {
&nbsp; &nbsp; initialRouteName: 'Product',
&nbsp; &nbsp; navigationOptions: {
&nbsp; &nbsp; &nbsp; headerStyle: {
&nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: '#777777',
&nbsp; &nbsp; &nbsp; },
&nbsp; &nbsp; &nbsp; headerTintColor: '#fff',
&nbsp; &nbsp; &nbsp; headerTitleStyle: {
&nbsp; &nbsp; &nbsp; &nbsp; fontWeight: 'bold',
&nbsp; &nbsp; &nbsp; },
&nbsp; &nbsp; },
&nbsp; },
);

const RootContainer = createAppContainer(RootStack);

export default class App extends React.Component {
&nbsp; render() {
&nbsp; &nbsp; return <RootContainer />;
&nbsp; }
}

const styles = StyleSheet.create({
&nbsp; container: {
&nbsp; &nbsp; flex: 1,
&nbsp; &nbsp; backgroundColor: '#fff',
&nbsp; &nbsp; alignItems: 'center',
&nbsp; &nbsp; justifyContent: 'center',
&nbsp; },
});

After Re-run the React Native app on the iOS/Android Device/Simulator you will see this updated views.

3. Install and Configure React Native SQLite Storage

Before creating an offline CRUD application using local data, we have to install the react-native-sqlite-storage and required UI/UX module.

yarn add react-native-sqlite-storage --save
yarn add react-native-elements --save
react-native link

We will use separate Class for accessing SQLite and do some CRUD (create, read, update, delete) operations. For that, create a new Javascript file on the root of the project folder.

touch Database.js

Open and edit Database.js then add this SQLite import with the configuration.

import SQLite from "react-native-sqlite-storage";
SQLite.DEBUG(true);
SQLite.enablePromise(true);

Add constant variable after that.

const database_name = "Reactoffline.db";
const database_version = "1.0";
const database_displayname = "SQLite React Offline Database";
const database_size = 200000;

Give this file a class name.

export default class Database {

}

Inside the class bracket, add a function for Database initialization that creates Database, tables, etc.

initDB() {
&nbsp; let db;
&nbsp; return new Promise((resolve) => {
&nbsp; &nbsp; console.log("Plugin integrity check ...");
&nbsp; &nbsp; SQLite.echoTest()
&nbsp; &nbsp; &nbsp; .then(() => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log("Integrity check passed ...");
&nbsp; &nbsp; &nbsp; &nbsp; console.log("Opening database ...");
&nbsp; &nbsp; &nbsp; &nbsp; SQLite.openDatabase(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; database_name,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; database_version,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; database_displayname,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; database_size
&nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(DB => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; db = DB;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Database OPEN");
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; db.executeSql('SELECT 1 FROM Product LIMIT 1').then(() => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Database is ready ... executing query ...");
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).catch((error) =>{
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Received error: ", error);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Database not yet ready ... populating data");
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; db.transaction((tx) => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tx.executeSql('CREATE TABLE IF NOT EXISTS Product (prodId, prodName, prodDesc, prodImage, prodPrice)');
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).then(() => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Table created successfully");
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).catch(error => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(error);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(db);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .catch(error => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(error);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; })
&nbsp; &nbsp; &nbsp; .catch(error => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log("echoTest failed - plugin not functional");
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; });
};

Add a function for close Database connection.

closeDatabase(db) {
&nbsp; if (db) {
&nbsp; &nbsp; console.log("Closing DB");
&nbsp; &nbsp; db.close()
&nbsp; &nbsp; &nbsp; .then(status => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log("Database CLOSED");
&nbsp; &nbsp; &nbsp; })
&nbsp; &nbsp; &nbsp; .catch(error => {
&nbsp; &nbsp; &nbsp; &nbsp; this.errorCB(error);
&nbsp; &nbsp; &nbsp; });
&nbsp; } else {
&nbsp; &nbsp; console.log("Database was not OPENED");
&nbsp; }
};

Add a function to get the list of products.

listProduct() {
&nbsp; return new Promise((resolve) => {
&nbsp; &nbsp; const products = [];
&nbsp; &nbsp; this.initDB().then((db) => {
&nbsp; &nbsp; &nbsp; db.transaction((tx) => {
&nbsp; &nbsp; &nbsp; &nbsp; tx.executeSql('SELECT p.prodId, p.prodName, p.prodImage FROM Product p', []).then(([tx,results]) => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Query completed");
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var len = results.rows.length;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (let i = 0; i < len; i++) {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let row = results.rows.item(i);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Prod ID: ${row.prodId}, Prod Name: ${row.prodName}`)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const { prodId, prodName, prodImage } = row;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; products.push({
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prodId,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prodName,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prodImage
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(products);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(products);
&nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; }).then((result) => {
&nbsp; &nbsp; &nbsp; &nbsp; this.closeDatabase(db);
&nbsp; &nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; });
&nbsp; }); &nbsp;
}

Add a function to get Product by ID.

productById(id) {
&nbsp; console.log(id);
&nbsp; return new Promise((resolve) => {
&nbsp; &nbsp; this.initDB().then((db) => {
&nbsp; &nbsp; &nbsp; db.transaction((tx) => {
&nbsp; &nbsp; &nbsp; &nbsp; tx.executeSql('SELECT * FROM Product WHERE prodId = ?', [id]).then(([tx,results]) => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(results);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(results.rows.length > 0) {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let row = results.rows.item(0);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(row);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; }).then((result) => {
&nbsp; &nbsp; &nbsp; &nbsp; this.closeDatabase(db);
&nbsp; &nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; });
&nbsp; }); &nbsp;
}

Add a function to save a new product to the SQLite database.

addProduct(prod) {
&nbsp; return new Promise((resolve) => {
&nbsp; &nbsp; this.initDB().then((db) => {
&nbsp; &nbsp; &nbsp; db.transaction((tx) => {
&nbsp; &nbsp; &nbsp; &nbsp; tx.executeSql('INSERT INTO Product VALUES (?, ?, ?, ?, ?)', [prod.prodId, prod.prodName, prod.prodDesc, prod.prodImage, prod.prodPrice]).then(([tx, results]) => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(results);
&nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; }).then((result) => {
&nbsp; &nbsp; &nbsp; &nbsp; this.closeDatabase(db);
&nbsp; &nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; });
&nbsp; }); &nbsp;
}

Add a function to update a product.

updateProduct(id, prod) {
&nbsp; return new Promise((resolve) => {
&nbsp; &nbsp; this.initDB().then((db) => {
&nbsp; &nbsp; &nbsp; db.transaction((tx) => {
&nbsp; &nbsp; &nbsp; &nbsp; tx.executeSql('UPDATE Product SET prodName = ?, prodDesc = ?, prodImage = ?, prodPrice = ? WHERE prodId = ?', [prod.prodName, prod.prodDesc, prod.prodImage, prod.prodPrice, id]).then(([tx, results]) => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(results);
&nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; }).then((result) => {
&nbsp; &nbsp; &nbsp; &nbsp; this.closeDatabase(db);
&nbsp; &nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; });
&nbsp; }); &nbsp;
}

Add a function to delete a product.

deleteProduct(id) {
&nbsp; return new Promise((resolve) => {
&nbsp; &nbsp; this.initDB().then((db) => {
&nbsp; &nbsp; &nbsp; db.transaction((tx) => {
&nbsp; &nbsp; &nbsp; &nbsp; tx.executeSql('DELETE FROM Product WHERE prodId = ?', [id]).then(([tx, results]) => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(results);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(results);
&nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; }).then((result) => {
&nbsp; &nbsp; &nbsp; &nbsp; this.closeDatabase(db);
&nbsp; &nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; });
&nbsp; }); &nbsp;
}

4. Show List of Product

To show or display the list of product, open and edit components/ProductScreen.js then replace all imports with these imports.

import React, { Component } from 'react';
import { StyleSheet, FlatList, ActivityIndicator, View, Text } from 'react-native';
import { ListItem, Button } from 'react-native-elements';
import Database from '../Database';

Instantiate the Database as a constant variable before the class name.

const db = new Database();

Next, replace navigationOptions with these.

static navigationOptions = ({ navigation }) => {
&nbsp; return {
&nbsp; &nbsp; title: 'Product List',
&nbsp; &nbsp; headerRight: (
&nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; buttonStyle={{ padding: 0, backgroundColor: 'transparent' }}
&nbsp; &nbsp; &nbsp; &nbsp; icon={{ name: 'add-circle', style: { marginRight: 0, fontSize: 28 } }}
&nbsp; &nbsp; &nbsp; &nbsp; onPress={() => {&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; navigation.navigate('AddProduct', {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onNavigateBack: this.handleOnNavigateBack
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; }}
&nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; ),
&nbsp; };
};

Add a constructor function.

constructor() {
&nbsp; super();
&nbsp; this.state = {
&nbsp; &nbsp; isLoading: true,
&nbsp; &nbsp; products: [],
&nbsp; &nbsp; notFound: 'Products not found.\nPlease click (+) button to add it.'
&nbsp; };
}

Add a function to initialize the screen.

componentDidMount() {
&nbsp; this._subscribe = this.props.navigation.addListener('didFocus', () => {
&nbsp; &nbsp; this.getProducts();
&nbsp; });
}

Add a function to get the product list from Database class.

getProducts() {
&nbsp; let products = [];
&nbsp; db.listProduct().then((data) => {
&nbsp; &nbsp; products = data;
&nbsp; &nbsp; this.setState({
&nbsp; &nbsp; &nbsp; products,
&nbsp; &nbsp; &nbsp; isLoading: false,
&nbsp; &nbsp; });
&nbsp; }).catch((err) => {
&nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; this.setState = {
&nbsp; &nbsp; &nbsp; isLoading: false
&nbsp; &nbsp; }
&nbsp; })
}

Add a variable to iterate the listed product in the view.

keyExtractor = (item, index) => index.toString()

Add a function to render the List Item.

renderItem = ({ item }) => (
&nbsp; <ListItem
&nbsp; &nbsp; title={item.prodName}
&nbsp; &nbsp; leftAvatar={{
&nbsp; &nbsp; &nbsp; source: item.prodImage && { uri: item.prodImage },
&nbsp; &nbsp; &nbsp; title: item.prodName[0]
&nbsp; &nbsp; }}
&nbsp; &nbsp; onPress={() => {
&nbsp; &nbsp; &nbsp; this.props.navigation.navigate('ProductDetails', {
&nbsp; &nbsp; &nbsp; &nbsp; prodId: `${item.prodId}`,
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; }}
&nbsp; &nbsp; chevron
&nbsp; &nbsp; bottomDivider
&nbsp; />
)

Add a function to render the rest of List view.

render() {
&nbsp; if(this.state.isLoading){
&nbsp; &nbsp; return(
&nbsp; &nbsp; &nbsp; <View style={styles.activity}>
&nbsp; &nbsp; &nbsp; &nbsp; <ActivityIndicator size="large" color="#0000ff"/>
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; )
&nbsp; }
&nbsp; if(this.state.products.length === 0){
&nbsp; &nbsp; return(
&nbsp; &nbsp; &nbsp; <View>
&nbsp; &nbsp; &nbsp; &nbsp; <Text style={styles.message}>{this.state.notFound}</Text>
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; )
&nbsp; }
&nbsp; return (
&nbsp; &nbsp; <FlatList
&nbsp; &nbsp; &nbsp; keyExtractor={this.keyExtractor}
&nbsp; &nbsp; &nbsp; data={this.state.products}
&nbsp; &nbsp; &nbsp; renderItem={this.renderItem}
&nbsp; &nbsp; />
&nbsp; );
}

Finally, add a stylesheet for the whole screen after the class bracket.

const styles = StyleSheet.create({
&nbsp; container: {
&nbsp; &nbsp;flex: 1,
&nbsp; &nbsp;paddingBottom: 22
&nbsp; },
&nbsp; item: {
&nbsp; &nbsp; padding: 10,
&nbsp; &nbsp; fontSize: 18,
&nbsp; &nbsp; height: 44,
&nbsp; },
&nbsp; activity: {
&nbsp; &nbsp; position: 'absolute',
&nbsp; &nbsp; left: 0,
&nbsp; &nbsp; right: 0,
&nbsp; &nbsp; top: 0,
&nbsp; &nbsp; bottom: 0,
&nbsp; &nbsp; alignItems: 'center',
&nbsp; &nbsp; justifyContent: 'center'
&nbsp; },
&nbsp; message: {
&nbsp; &nbsp; padding: 16,
&nbsp; &nbsp; fontSize: 18,
&nbsp; &nbsp; color: 'red'
&nbsp; }
});

5. Show Product Details and Delete Product

From the list of product view, you will see that list item has an action button to show the product details. Next, open and edit components/ProductDetailsScreen.js then replace the imports with these imports.

import React, { Component } from 'react';
import { ScrollView, StyleSheet, Image, ActivityIndicator, View, Text } from 'react-native';
import { Card, Button } from 'react-native-elements';
import Database from '../Database';

Instantiate the Database as a constant variable.

const db = new Database();

Add a function as the constructor.

constructor() {
&nbsp; super();
&nbsp; this.state = {
&nbsp; &nbsp; isLoading: true,
&nbsp; &nbsp; product: {},
&nbsp; &nbsp; id: '',
&nbsp; };
}

Add a function to initialize the screen.

componentDidMount() {
&nbsp; this._subscribe = this.props.navigation.addListener('didFocus', () => {
&nbsp; &nbsp; const { navigation } = this.props;
&nbsp; &nbsp; db.productById(navigation.getParam('prodId')).then((data) => {
&nbsp; &nbsp; &nbsp; console.log(data);
&nbsp; &nbsp; &nbsp; product = data;
&nbsp; &nbsp; &nbsp; this.setState({
&nbsp; &nbsp; &nbsp; &nbsp; product,
&nbsp; &nbsp; &nbsp; &nbsp; isLoading: false,
&nbsp; &nbsp; &nbsp; &nbsp; id: product.prodId
&nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; }).catch((err) => {
&nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; this.setState = {
&nbsp; &nbsp; &nbsp; &nbsp; isLoading: false
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; })
&nbsp; });
}

Add a function to delete a product data.

deleteProduct(id) {
&nbsp; const { navigation } = this.props;
&nbsp; this.setState({
&nbsp; &nbsp; isLoading: true
&nbsp; });
&nbsp; db.deleteProduct(id).then((result) => {
&nbsp; &nbsp; console.log(result);
&nbsp; &nbsp; this.props.navigation.goBack();
&nbsp; }).catch((err) => {
&nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; this.setState = {
&nbsp; &nbsp; &nbsp; isLoading: false
&nbsp; &nbsp; }
&nbsp; })
}

Add a function to render the whole Product Details view.

render() {
&nbsp; if(this.state.isLoading){
&nbsp; &nbsp; return(
&nbsp; &nbsp; &nbsp; <View style={styles.activity}>
&nbsp; &nbsp; &nbsp; &nbsp; <ActivityIndicator size="large" color="#0000ff" />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; )
&nbsp; }
&nbsp; return (
&nbsp; &nbsp; <ScrollView>
&nbsp; &nbsp; &nbsp; <Card style={styles.container}>
&nbsp; &nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Image
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; style={{width: 150, height: 150}}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; source={{uri: this.state.product.prodImage}}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Text style={{fontSize: 16}}>Product ID: {this.state.product.prodId}</Text>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Text style={{fontSize: 16}}>Product Name: {this.state.product.prodName}</Text>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Text style={{fontSize: 16}}>Product Desc: {this.state.product.prodDesc}</Text>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <View>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Text style={{fontSize: 16}}>Product Price: {this.state.product.prodPrice}</Text>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; &nbsp; <View style={styles.detailButton}>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; large
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundColor={'#CCCCCC'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leftIcon={{name: 'edit'}}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title='Edit'
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.props.navigation.navigate('EditProduct', {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prodId: `${this.state.id}`,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }} />
&nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; &nbsp; <View style={styles.detailButton}>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; large
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundColor={'#999999'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color={'#FFFFFF'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leftIcon={{name: 'delete'}}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title='Delete'
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.deleteProduct(this.state.id)} />
&nbsp; &nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; </Card>
&nbsp; &nbsp; </ScrollView>
&nbsp; );
}

Finally, add the stylesheet for this screen after the class bracket.

const styles = StyleSheet.create({
&nbsp; container: {
&nbsp; &nbsp; flex: 1,
&nbsp; &nbsp; padding: 20
&nbsp; },
&nbsp; subContainer: {
&nbsp; &nbsp; flex: 1,
&nbsp; &nbsp; paddingBottom: 20,
&nbsp; &nbsp; borderBottomWidth: 2,
&nbsp; &nbsp; borderBottomColor: '#CCCCCC',
&nbsp; },
&nbsp; activity: {
&nbsp; &nbsp; position: 'absolute',
&nbsp; &nbsp; left: 0,
&nbsp; &nbsp; right: 0,
&nbsp; &nbsp; top: 0,
&nbsp; &nbsp; bottom: 0,
&nbsp; &nbsp; alignItems: 'center',
&nbsp; &nbsp; justifyContent: 'center'
&nbsp; },
&nbsp; detailButton: {
&nbsp; &nbsp; marginTop: 10
&nbsp; }
})

6. Add Product

To add or save a new Product, open and edit the components/ProductAddScreen.js then replace all imports with these imports.

import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, View, TextInput } from 'react-native';
import { Button } from 'react-native-elements';
import Database from '../Database';

Instantiate the Database as a constant variable.

const db = new Database();

Add a constructor inside the class bracket after the navigationOptions.

constructor() {
&nbsp; super();
&nbsp; this.state = {
&nbsp; &nbsp; prodId: '',
&nbsp; &nbsp; prodName: '',
&nbsp; &nbsp; prodDesc: '',
&nbsp; &nbsp; prodImage: '',
&nbsp; &nbsp; prodPrice: '0',
&nbsp; &nbsp; isLoading: false,
&nbsp; };
}

Add a function to update the input text values.

updateTextInput = (text, field) => {
&nbsp; const state = this.state
&nbsp; state[field] = text;
&nbsp; this.setState(state);
}

Add a function to save a product to the SQLite table.

saveProduct() {
&nbsp; this.setState({
&nbsp; &nbsp; isLoading: true,
&nbsp; });
&nbsp; let data = {
&nbsp; &nbsp; prodId: this.state.prodId,
&nbsp; &nbsp; prodName: this.state.prodName,
&nbsp; &nbsp; prodDesc: this.state.prodDesc,
&nbsp; &nbsp; prodImage: this.state.prodImage,
&nbsp; &nbsp; prodPrice: this.state.prodPrice
&nbsp; }
&nbsp; db.addProduct(data).then((result) => {
&nbsp; &nbsp; console.log(result);
&nbsp; &nbsp; this.setState({
&nbsp; &nbsp; &nbsp; isLoading: false,
&nbsp; &nbsp; });
&nbsp; &nbsp; this.props.navigation.state.params.onNavigateBack;
&nbsp; &nbsp; this.props.navigation.goBack();
&nbsp; }).catch((err) => {
&nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; this.setState({
&nbsp; &nbsp; &nbsp; isLoading: false,
&nbsp; &nbsp; });
&nbsp; })
}

Add a function to render the whole add product view.

render() {
&nbsp; if(this.state.isLoading){
&nbsp; &nbsp; return(
&nbsp; &nbsp; &nbsp; <View style={styles.activity}>
&nbsp; &nbsp; &nbsp; &nbsp; <ActivityIndicator size="large" color="#0000ff"/>
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; )
&nbsp; }
&nbsp; return (
&nbsp; &nbsp; <ScrollView style={styles.container}>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product ID'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodId}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodId')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Name'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodName}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodName')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; multiline={true}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numberOfLines={4}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Description'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodDesc}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodDesc')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Image'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodImage}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodImage')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Price'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodPrice}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyboardType='numeric'
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodPrice')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.button}>
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; large
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leftIcon={{name: 'save'}}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title='Save'
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.saveProduct()} />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; </ScrollView>
&nbsp; );
}

Finally, add the style for the whole screen.

const styles = StyleSheet.create({
&nbsp; container: {
&nbsp; &nbsp; flex: 1,
&nbsp; &nbsp; padding: 20
&nbsp; },
&nbsp; subContainer: {
&nbsp; &nbsp; flex: 1,
&nbsp; &nbsp; marginBottom: 20,
&nbsp; &nbsp; padding: 5,
&nbsp; &nbsp; borderBottomWidth: 2,
&nbsp; &nbsp; borderBottomColor: '#CCCCCC',
&nbsp; },
&nbsp; activity: {
&nbsp; &nbsp; position: 'absolute',
&nbsp; &nbsp; left: 0,
&nbsp; &nbsp; right: 0,
&nbsp; &nbsp; top: 0,
&nbsp; &nbsp; bottom: 0,
&nbsp; &nbsp; alignItems: 'center',
&nbsp; &nbsp; justifyContent: 'center'
&nbsp; }
})

7. Edit Product

To edit a product, open and edit components/ProductEditScreen.js then replace all imports with these imports.

import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, View, TextInput } from 'react-native';
import { Button } from 'react-native-elements';
import Database from '../Database';

Instantiate the Database as a constant variable.

const db = new Database();

Add the constructor after the navigationOptions function.

constructor() {
&nbsp; super();
&nbsp; this.state = {
&nbsp; &nbsp; prodId: '',
&nbsp; &nbsp; prodName: '',
&nbsp; &nbsp; prodDesc: '',
&nbsp; &nbsp; prodImage: '',
&nbsp; &nbsp; prodPrice: '0',
&nbsp; &nbsp; isLoading: true,
&nbsp; };
}

Add a function to initialize the screen that will get product data.

componentDidMount() {
&nbsp; const { navigation } = this.props;
&nbsp; db.productById(navigation.getParam('prodId')).then((data) => {
&nbsp; &nbsp; console.log(data);
&nbsp; &nbsp; const product = data;
&nbsp; &nbsp; this.setState({
&nbsp; &nbsp; &nbsp; prodId: product.prodId,
&nbsp; &nbsp; &nbsp; prodName: product.prodName,
&nbsp; &nbsp; &nbsp; prodDesc: product.prodDesc,
&nbsp; &nbsp; &nbsp; prodImage: product.prodImage,
&nbsp; &nbsp; &nbsp; prodPrice: product.prodPrice,
&nbsp; &nbsp; &nbsp; isLoading: false,
&nbsp; &nbsp; });
&nbsp; }).catch((err) => {
&nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; this.setState = {
&nbsp; &nbsp; &nbsp; isLoading: false
&nbsp; &nbsp; }
&nbsp; })
}

Add a function to update the input text value.

updateTextInput = (text, field) => {
&nbsp; const state = this.state
&nbsp; state[field] = text;
&nbsp; this.setState(state);
}

Add a function to update the product data.

updateProduct() {
&nbsp; this.setState({
&nbsp; &nbsp; isLoading: true,
&nbsp; });
&nbsp; const { navigation } = this.props;
&nbsp; let data = {
&nbsp; &nbsp; prodId: this.state.prodId,
&nbsp; &nbsp; prodName: this.state.prodName,
&nbsp; &nbsp; prodDesc: this.state.prodDesc,
&nbsp; &nbsp; prodImage: this.state.prodImage,
&nbsp; &nbsp; prodPrice: this.state.prodPrice
&nbsp; }
&nbsp; db.updateProduct(data.prodId, data).then((result) => {
&nbsp; &nbsp; console.log(result);
&nbsp; &nbsp; this.setState({
&nbsp; &nbsp; &nbsp; isLoading: false,
&nbsp; &nbsp; });
&nbsp; &nbsp; this.props.navigation.state.params.onNavigateBack;
&nbsp; &nbsp; this.props.navigation.goBack();
&nbsp; }).catch((err) => {
&nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; this.setState({
&nbsp; &nbsp; &nbsp; isLoading: false,
&nbsp; &nbsp; });
&nbsp; })
}

Add a function to render the whole Edit Product screen.

render() {
&nbsp; if(this.state.isLoading){
&nbsp; &nbsp; return(
&nbsp; &nbsp; &nbsp; <View style={styles.activity}>
&nbsp; &nbsp; &nbsp; &nbsp; <ActivityIndicator size="large" color="#0000ff"/>
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; )
&nbsp; }
&nbsp; return (
&nbsp; &nbsp; <ScrollView style={styles.container}>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product ID'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodId}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodId')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Name'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodName}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodName')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; multiline={true}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numberOfLines={4}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Description'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodDesc}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodDesc')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Image'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodImage}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodImage')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.subContainer}>
&nbsp; &nbsp; &nbsp; &nbsp; <TextInput
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder={'Product Price'}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={this.state.prodPrice}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyboardType='numeric'
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChangeText={(text) => this.updateTextInput(text, 'prodPrice')}
&nbsp; &nbsp; &nbsp; &nbsp; />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; &nbsp; <View style={styles.button}>
&nbsp; &nbsp; &nbsp; &nbsp; <Button
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; large
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leftIcon={{name: 'save'}}
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title='Save'
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onPress={() => this.updateProduct()} />
&nbsp; &nbsp; &nbsp; </View>
&nbsp; &nbsp; </ScrollView>
&nbsp; );
}

Finally, add the stylesheet after the class bracket.

const styles = StyleSheet.create({
&nbsp; container: {
&nbsp; &nbsp; flex: 1,
&nbsp; &nbsp; padding: 20
&nbsp; },
&nbsp; subContainer: {
&nbsp; &nbsp; flex: 1,
&nbsp; &nbsp; marginBottom: 20,
&nbsp; &nbsp; padding: 5,
&nbsp; &nbsp; borderBottomWidth: 2,
&nbsp; &nbsp; borderBottomColor: '#CCCCCC',
&nbsp; },
&nbsp; activity: {
&nbsp; &nbsp; position: 'absolute',
&nbsp; &nbsp; left: 0,
&nbsp; &nbsp; right: 0,
&nbsp; &nbsp; top: 0,
&nbsp; &nbsp; bottom: 0,
&nbsp; &nbsp; alignItems: 'center',
&nbsp; &nbsp; justifyContent: 'center'
&nbsp; }
})

8. Run and Test React Native and SQLite Offline Mobile App

As we show you at the first step, run the React Native and SQLite app using this command.

react-native run-android
react-native run-ios

After the new terminal window open, just go to the project folder then run this command.

react-native start

Now, you will see the whole application in the Android/iOS Device.

That it’s, the React Native and SQLite Offline Mobile App. You can get the full source code from our GitHub.

How to CRUD Operations using Reactjs and ASP.NET Web API

How to CRUD Operations using Reactjs and ASP.NET Web API

In this article, I'm going to perform CRUD operations using React.js, ASP.NET Web API and SQL Server. ReactJS is an open-source JavaScript library that is used for creating user interfaces. It is developed and maintained by Facebook.

Introduction

In this article, I'm going to perform CRUD operations using  React.js and ASP.NET Web API. Reactjs is an open-source JavaScript library that is used for creating user interfaces. It is developed and maintained by Facebook. Learn more about React here.

Prerequisites

  • We should have the basic knowledge of React.js and Web API.
  • Visual Studio and Visual Studio Code IDE should be installed on your system.
  • SQL Server Management Studio.

Technologies we will use:

  • ASP.NET Web API.
  • ReactJS
  • SQL Server.
  • React strap.
  • Bootstrap

You may also like: Angular vs React vs Vue: Which one will be popular in 2020.

Step 1: Create a Table in the Database

Open SQL Server Management Studio, create a database named "CrudDemo," and in this database, create a table. Give that table a name like "studentmaster."

USE [CrudDemo]  
GO  
CREATE TABLE [dbo].[studentmaster](  
    [Id] [int] IDENTITY(1,1) NOT NULL,  
    [Name] [varchar](50) NULL,  
    [RollNo] [varchar](50) NULL,  
    [Class] [varchar](50) NULL,  
    [Address] [varchar](50) NULL,  
 CONSTRAINT [PK_studentmaster] PRIMARY KEY CLUSTERED   
(  
    [Id] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  

GO  
Create a New Web API Project

Step 2: Create a New Project.

Creating a new project in VS Code

_Creating a new project in VS Code_

Step 3: Change the Name to CrudUsingReact

Changing project name to CrudUsingReact

_Changing project name to CrudUsingReact_

Step 4: Choose the Web API Template

Selecting Web API template

_Selecting Web API template_

Step 5

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.

Adding data

_Adding data_

Step 6

Click on the "ADO.NET Entity Data Model" option and click "Add."

Adding Entity Data Model

_Adding Entity Data Model_

Step 7

Select EF Designer from the database and click the "Next" button.

Choosing EF Designer

_Choosing EF Designer_

Step 8

Add the connection properties and select database name on the next page and click OK.

Adding connection properties to db

_Adding connection properties to db_

Step 9

Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button.

Finishing project setup

_Finishing project setup_

Step 10

Right-click on Models folder and add two classes — Student and Response. Now, paste the following codes in these classes:

public class Student  
   {  
       public string Name { get; set; }  
       public string Rollno { get; set; }  
       public string Class { get; set; }  
       public string Address { get; set; }  
   }  
public class Response  
   {  
       public string Status { get; set; }  
       public string Message { get; set; }  
   }  

Step 11

Right-click on the Controllers folder and add a new controller. Name it "Student controller" and add the following namespace in the Student controller.

using CrudUsingReact.Models;  

Step 12

Now, add a method to insert and update data into the database.

[Route("AddotrUpdatestudent")]  
       [HttpPost]  
       public object AddotrUpdatestudent(Student st)  
       {  
           try  
           {  
               if (st.Id == 0)  
               {  
                   studentmaster sm = new studentmaster();  
                   sm.Name = st.Name;  
                   sm.RollNo = st.Rollno;  
                   sm.Address = st.Address;  
                   sm.Class = st.Class;  
                   DB.studentmasters.Add(sm);  
                   DB.SaveChanges();  
                   return new Response  
                   {  
                       Status = "Success",  
                       Message = "Data Successfully"  
                   };  
               }  
               else  
               {  
                   var obj = DB.studentmasters.Where(x => x.Id == st.Id).ToList().FirstOrDefault();  
                   if (obj.Id > 0)  
                   {  

                       obj.Name = st.Name;  
                       obj.RollNo = st.Rollno;  
                       obj.Address = st.Address;  
                       obj.Class = st.Class;  
                       DB.SaveChanges();  
                       return new Response  
                       {  
                           Status = "Updated",  
                           Message = "Updated Successfully"  
                       };  
                   }  
               }  
           }  
           catch (Exception ex)  
           {  
               Console.Write(ex.Message);  
           }  
           return new Response  
           {  
               Status = "Error",  
               Message = "Data not insert"  
           };  

       }  

Step 13

Add other methods to delete and fetch data respectively from the database.

[Route("Deletestudent")]  
      [HttpDelete]  
      public object Deletestudent(int id)  
      {  
          var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
          DB.studentmasters.Remove(obj);  
          DB.SaveChanges();  
          return new Response  
          {  
              Status = "Delete",  
              Message = "Delete Successfuly"  
          };  
      }  

[HttpGet]  
      public object   Studentdetails()  
      {  

              var a = DB.studentmasters.ToList();  
              return a;  
      }  

Complete Student Controller Code

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
using CrudUsingReact.Models;  

namespace CrudUsingReact.Controllers  
{  
    [RoutePrefix("Api/Student")]  
    public class studentController : ApiController  
    {  
        CrudDemoEntities DB = new CrudDemoEntities();  
        [Route("AddotrUpdatestudent")]  
        [HttpPost]  
        public object AddotrUpdatestudent(Student st)  
        {  
            try  
            {  
                if (st.Id == 0)  
                {  
                    studentmaster sm = new studentmaster();  
                    sm.Name = st.Name;  
                    sm.RollNo = st.RollNo;  
                    sm.Address = st.Address;  
                    sm.Class = st.Class;  
                    DB.studentmasters.Add(sm);  
                    DB.SaveChanges();  
                    return new Response  
                    {  
                        Status = "Success",  
                        Message = "Data Successfully"  
                    };  
                }  
                else  
                {  
                    var obj = DB.studentmasters.Where(x => x.Id == st.Id).ToList().FirstOrDefault();  
                    if (obj.Id > 0)  
                    {  

                        obj.Name = st.Name;  
                        obj.RollNo = st.RollNo;  
                        obj.Address = st.Address;  
                        obj.Class = st.Class;  
                        DB.SaveChanges();  
                        return new Response  
                        {  
                            Status = "Updated",  
                            Message = "Updated Successfully"  
                        };  
                    }  
                }  
            }  
            catch (Exception ex)  
            {  
                Console.Write(ex.Message);  
            }  
            return new Response  
            {  
                Status = "Error",  
                Message = "Data not insert"  
            };  

        }  
        [Route("Studentdetails")]  
        [HttpGet]  
        public object   Studentdetails()  
        {  

                var a = DB.studentmasters.ToList();  
                return a;  
        }  

        [Route("StudentdetailById")]  
        [HttpGet]  
        public object StudentdetailById(int id)  
        {  
            var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
            return obj;  
        }  
        [Route("Deletestudent")]  
        [HttpDelete]  
        public object Deletestudent(int id)  
        {  
            var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
            DB.studentmasters.Remove(obj);  
            DB.SaveChanges();  
            return new Response  
            {  
                Status = "Delete",  
                Message = "Delete Successfuly"  
            };  
        }  
    }  
}  

Step 14

Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines:

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");    
config.EnableCors(cors);   
Create React.js Project

Step 15

To create a new ReactJS project, open the command prompt, and enter the following command:

npx create-react-app crudwithceactjs  

Open the newly created project in Visual Studio Code and install Reactstrap and Bootstrap by using the following commands:

npm install --save bootstrap  
npm install --save reactstrap react react-dom  

Step 16

Now, go to the "src" folder and add a new folder "Student" and four new components:

  1. Addstudent.js
  2. Studentlist.js
  3. Editstudent.js
  4. Table.js

Adding components to Student folder

_Adding components to the Student folder_

Step 17

Install the Axios library by using the following command. Learn more about Axios library

npm install --save axios  

Step 18

Add routing: Use the following command to add routing in React.

npm install react-router-dom --save    

Step 19

Now, open the Addstudent.js file and add the following code:

import React from 'react';  
import axios from 'axios';  
import '../Student/Addstudent.css'  
import { Container, Col, Form, Row, FormGroup, Label, Input, Button } from 'reactstrap';  
class Addstudent extends React.Component{  
constructor(props){  
super(props)  
this.state = {  
Name:'',  
RollNo:'',  
Class:'',  
Address:''  
}  
}   
Addstudent=()=>{  
  axios.post('http://localhost:52564/Api/Student/AddotrUpdatestudent/', {Name:this.state.Name,RollNo:this.state.RollNo,  
  Class:this.state.Class, Address:this.state.Address})  
.then(json => {  
if(json.data.Status==='Success'){  
  console.log(json.data.Status);  
  alert("Data Save Successfully");  
this.props.history.push('/Studentlist')  
}  
else{  
alert('Data not Saved');  
debugger;  
this.props.history.push('/Studentlist')  
}  
})  
}  

handleChange= (e)=> {  
this.setState({[e.target.name]:e.target.value});  
}  

render() {  
return (  
   <Container className="App">  
    <h4 className="PageHeading">Enter Student Informations</h4>  
    <Form className="form">  
      <Col>  
        <FormGroup row>  
          <Label for="name" sm={2}>Name</Label>  
          <Col sm={10}>  
            <Input type="text" name="Name" onChange={this.handleChange} value={this.state.Name} placeholder="Enter Name" />  
          </Col>  
        </FormGroup>  
        <FormGroup row>  
          <Label for="address" sm={2}>RollNo</Label>  
          <Col sm={10}>  
            <Input type="text" name="RollNo" onChange={this.handleChange} value={this.state.RollNo} placeholder="Enter RollNo" />  
          </Col>  
        </FormGroup>  
        <FormGroup row>  
          <Label for="Password" sm={2}>Class</Label>  
          <Col sm={10}>  
            <Input type="text" name="Class" onChange={this.handleChange} value={this.state.Class} placeholder="Enter Class" />  
          </Col>  
        </FormGroup>  
        <FormGroup row>  
          <Label for="Password" sm={2}>Address</Label>  
          <Col sm={10}>  
            <Input type="text" name="Address" onChange={this.handleChange} value={this.state.Address} placeholder="Enter Address" />  
          </Col>  
        </FormGroup>  
      </Col>  
      <Col>  
        <FormGroup row>  
          <Col sm={5}>  
          </Col>  
          <Col sm={1}>  
          <button type="button" onClick={this.Addstudent} className="btn btn-success">Submit</button>  
          </Col>  
          <Col sm={1}>  
            <Button color="danger">Cancel</Button>{' '}  
          </Col>  
          <Col sm={5}>  
          </Col>  
        </FormGroup>  
      </Col>  
    </Form>  
  </Container>  
);  
}  

}  

export default Addstudent;  

Add a new file  Addstudet.css file and add the following CSS classes. Import this file in the  Addstudent.js component.

.PageHeading    
{    
  margin-top: 10px;    
  margin-bottom: 10px;    
  color :black !important;    
}    

Step 20

Now, add a Table.js file and add the following code:

import React, { Component } from 'react';  
import axios from 'axios';  
import { Link } from 'react-router-dom';  
class Table extends Component {  
  constructor(props) {  
    super(props);  
    }  

    DeleteStudent= () =>{  
     axios.delete('http://localhost:52564/Api/Student/Deletestudent?id='+this.props.obj.Id)  
    .then(json => {  
    if(json.data.Status==='Delete'){  
    alert('Record deleted successfully!!');  
    }  
    })  
    }  
  render() {  
    return (  
        <tr>  
          <td>  
            {this.props.obj.Name}  
          </td>  
          <td>  
            {this.props.obj.RollNo}  
          </td>  
          <td>  
            {this.props.obj.Class}  
          </td>  
          <td>  
            {this.props.obj.Address}  
          </td>  
          <td>  
          <Link to={"/edit/"+this.props.obj.Id} className="btn btn-success">Edit</Link>  
          </td>  
          <td>  
            <button type="button" onClick={this.DeleteStudent} className="btn btn-danger">Delete</button>  
          </td>  
        </tr>  
    );  
  }  
}  

export default Table;  

Step 21

Now, add a studentlist.js file and add the following code.

import React, { Component } from 'react';  
import axios from 'axios';  
import Table from './Table';  

export default class Studentlist extends Component {  

  constructor(props) {  
      super(props);  
      this.state = {business: []};  
    }  
    componentDidMount(){  
      debugger;  
      axios.get('http://localhost:52564/Api/Student/Studentdetails')  
        .then(response => {  
          this.setState({ business: response.data });  
          debugger;  

        })  
        .catch(function (error) {  
          console.log(error);  
        })  
    }  

    tabRow(){  
      return this.state.business.map(function(object, i){  
          return <Table obj={object} key={i} />;  
      });  
    }  

    render() {  
      return (  
        <div>  
          <h4 align="center">Student List</h4>  
          <table className="table table-striped" style={{ marginTop: 10 }}>  
            <thead>  
              <tr>  
                <th>Name</th>  
                <th>RollNo</th>  
                <th>Class</th>  
                <th>Address</th>  
                <th colSpan="4">Action</th>  
              </tr>  
            </thead>  
            <tbody>  
             { this.tabRow() }   
            </tbody>  
          </table>  
        </div>  
      );  
    }  
  }  

Step 22

Add EditStudent.js file with the following code:

import React from 'react';   
import { Container, Col, Form, Row, FormGroup, Label, Input, Button } from 'reactstrap';  
import axios from 'axios'  
import '../Student/Addstudent.css'  
class Edit extends React.Component {  
    constructor(props) {  
        super(props)  

    this.onChangeName = this.onChangeName.bind(this);  
    this.onChangeRollNo = this.onChangeRollNo.bind(this);  
    this.onChangeClass = this.onChangeClass.bind(this);  
    this.onChangeAddress = this.onChangeAddress.bind(this);  
    this.onSubmit = this.onSubmit.bind(this);  

         this.state = {  
            Name: '',  
            RollNo: '',  
            Class: '',  
            Address: ''  

        }  
    }  

  componentDidMount() {  
      axios.get('http://localhost:52564/Api/Student/StudentdetailById?id='+this.props.match.params.id)  
          .then(response => {  
              this.setState({   
                Name: response.data.Name,   
                RollNo: response.data.RollNo,  
                Class: response.data.Class,  
                Address: response.data.Address });  

          })  
          .catch(function (error) {  
              console.log(error);  
          })  
    }  

  onChangeName(e) {  
    this.setState({  
        Name: e.target.value  
    });  
  }  
  onChangeRollNo(e) {  
    this.setState({  
        RollNo: e.target.value  
    });    
  }  
  onChangeClass(e) {  
    this.setState({  
        Class: e.target.value  
    });  
}  
    onChangeAddress(e) {  
        this.setState({  
            Address: e.target.value  
        });  
  }  

  onSubmit(e) {  
    debugger;  
    e.preventDefault();  
    const obj = {  
        Id:this.props.match.params.id,  
      Name: this.state.Name,  
      RollNo: this.state.RollNo,  
      Class: this.state.Class,  
      Address: this.state.Address  

    };  
    axios.post('http://localhost:52564/Api/Student/AddotrUpdatestudent/', obj)  
        .then(res => console.log(res.data));  
        debugger;  
        this.props.history.push('/Studentlist')  
  }  
    render() {  
        return (  
            <Container className="App">  

             <h4 className="PageHeading">Update Student Informations</h4>  
                <Form className="form" onSubmit={this.onSubmit}>  
                    <Col>  
                        <FormGroup row>  
                            <Label for="name" sm={2}>Name</Label>  
                            <Col sm={10}>  
                                <Input type="text" name="Name" value={this.state.Name} onChange={this.onChangeName}  
                                placeholder="Enter Name" />  
                            </Col>  
                        </FormGroup>  
                        <FormGroup row>  
                            <Label for="Password" sm={2}>RollNo</Label>  
                            <Col sm={10}>  
                                <Input type="text" name="RollNo" value={this.state.RollNo} onChange={this.onChangeRollNo} placeholder="Enter RollNo" />  
                            </Col>  
                        </FormGroup>  
                         <FormGroup row>  
                            <Label for="Password" sm={2}>Class</Label>  
                            <Col sm={10}>  
                                <Input type="text" name="Class" value={this.state.Class} onChange={this.onChangeClass} placeholder="Enter Class" />  
                            </Col>  
                        </FormGroup>  
                         <FormGroup row>  
                            <Label for="Password" sm={2}>Address</Label>  
                            <Col sm={10}>  
                                <Input type="text" name="Address"value={this.state.Address} onChange={this.onChangeAddress} placeholder="Enter Address" />  
                            </Col>  
                        </FormGroup>   
                    </Col>  
                    <Col>  
                        <FormGroup row>  
                            <Col sm={5}>  
                            </Col>  
                            <Col sm={1}>  
                          <Button type="submit" color="success">Submit</Button>{' '}  
                            </Col>  
                            <Col sm={1}>  
                                <Button color="danger">Cancel</Button>{' '}  
                            </Col>  
                            <Col sm={5}>  
                            </Col>  
                        </FormGroup>  
                    </Col>  
                </Form>  
            </Container>  
        );  
    }  

}  

export default Edit;  

Step 23

Open the App.js file with the following code in it.

import React from 'react';  
import Addstudent from './Student/Addstudent';  
import Studentlist from './Student/Studentlist';  
import EditStudent from './Student/EditStudent';  
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';  
import './App.css';  
function App() {  
  return (  
    <Router>  
      <div className="container">  
        <nav className="navbar navbar-expand-lg navheader">  
          <div className="collapse navbar-collapse" >  
            <ul className="navbar-nav mr-auto">  
              <li className="nav-item">  
                <Link to={'/Addstudent'} className="nav-link">Addstudent</Link>  
              </li>  
              <li className="nav-item">  
                <Link to={'/Studentlist'} className="nav-link">Student List</Link>  
              </li>  
            </ul>  
          </div>  
        </nav> <br />  
        <Switch>  
          <Route exact path='/Addstudent' component={Addstudent} />  
          <Route path='/edit/:id' component={EditStudent} />  
          <Route path='/Studentlist' component={Studentlist} />  
        </Switch>  
      </div>  
    </Router>  
  );  
}  

export default App;  

Add the following CSS classes in the App.css file.

.App {    
  text-align: center;    
}    
.navheader{    
  margin-top: 10px;    
  color :black !important;    
  background-color: #b3beca!important    
}    

Now, run the application by using the  npm start command and check the result.

Student List application view

Click on the Add Student button to add a new record into the database.

Adding a new student into the database

Click on the Edit button to update a record.

Updating a record in the database

Click on the Delete button to delete a record.

Deleting a record in the database

Summary

In this article, we learned how to perform CRUD operations using React, Asp.net Web API, and SQL Server.

Thank for reading. Please share if you liked it!

Build a CRUD App with ASP.NET Core 2.2 and SQL Server

Build a CRUD App with ASP.NET Core 2.2 and SQL Server

​ I’ve always said that you can tell a lot about a person by the kind of music they listen to. Don’t tell me you haven’t had serious doubts about whether you can be friends with someone when you find out that they like a particular band or artist. In that spirit, I created *JudgeMyTaste*, an ASP.NET Core web application where people can enter their favorite band or artist so that people on the Internet can judge them openly. ​ The combination of ASP.NET and SQL Server is probably the most common pairing in the enterprises that use ASP.NET. With ASP.NET Core and SQL Server both being cross-platform, you don’t *have* to run this combination on Windows anymore! I’ll show you how to create a basic CRUD application using ASP.NET Core 2.2 and SQL Server 2017. I’ll be running on Linux, but with the free tools used here, it won’t matter what operating system you’re using! ​ The tools I’ll be using that are available for all platforms are: * SQL Server 2017 (I’ll be running on Ubuntu 18.04) * Visual Studio Code * Azure Data Studio * ASP.NET Core 2.2 ​ Once you’ve got all the tools installed for your platform, let’s rock and roll! ​ ​ ​ ## Scaffold Your ASP.NET Core 2.2 Application ​ No matter the platform you’re on, the ```dotnet``` CLI is available. The commands used here should be the same for everyone. To scaffold the ASP.NET Core 2.2 MVC application, create a new folder for it: I’ve always said that you can tell a lot about a person by the kind of music they listen to. Don’t tell me you haven’t had serious doubts about whether you can be friends with someone when you find out that they like a particular band or artist. In that spirit, I created JudgeMyTaste, an ASP.NET Core web application where people can enter their favorite band or artist so that people on the Internet can judge them openly.

I’ve always said that you can tell a lot about a person by the kind of music they listen to. Don’t tell me you haven’t had serious doubts about whether you can be friends with someone when you find out that they like a particular band or artist. In that spirit, I created JudgeMyTaste, an ASP.NET Core web application where people can enter their favorite band or artist so that people on the Internet can judge them openly.

The combination of ASP.NET and SQL Server is probably the most common pairing in the enterprises that use ASP.NET. With ASP.NET Core and SQL Server both being cross-platform, you don’t have to run this combination on Windows anymore! I’ll show you how to create a basic CRUD application using ASP.NET Core 2.2 and SQL Server 2017. I’ll be running on Linux, but with the free tools used here, it won’t matter what operating system you’re using!

The tools I’ll be using that are available for all platforms are:

  • SQL Server 2017 (I’ll be running on Ubuntu 18.04)
  • Visual Studio Code
  • Azure Data Studio
  • ASP.NET Core 2.2

Once you’ve got all the tools installed for your platform, let’s rock and roll!

Scaffold Your ASP.NET Core 2.2 Application

No matter the platform you’re on, the dotnet CLI is available. The commands used here should be the same for everyone. To scaffold the ASP.NET Core 2.2 MVC application, create a new folder for it:

mkdir JudgeMyTaste

Change into that new directory:

cd JudgeMyTaste

Then run the following command:

dotnet new mvc

Then open the new application in VS Code.

code .

When you open the new application in VS Code, you should get a warning in the bottom right corner asking to add some missing assets. Go ahead and add the missing assets. You’ll see the .vscode folder added with a launch.json and a tasks.json file.

These will allow you to run the application from VS Code. To verify that everything scaffolded properly, run the base application by typing F5. This will build the application, run it, and open it in a new browser window.

You may notice a strange error page come up, if you’ve never run an ASP.NET Core 2.x application before. By default ASP.NET Core wants to run on HTTPS. This is a recommended practice for web applications. You could avoid this message by removing the redirect to HTTPS in your Startup.cs or by generating a certificate for your local machine, but this error screen only comes up once in a great while, so I just side step it by clicking on Advanced and telling the browser that it’s okay to visit this site even though there is no certificate for it.

For your daily work, it will probably behoove you to create a local certificate for development so that you never have to see this message again.

Create Your SQL Server Database

Open Azure Data Studio and connect to your localhost server with the SA password you created when installing SQL Server on your machine. You’ll notice it is arranged very much like VS Code. In the Connections Explorer, you will see localhost as a connection. Right-click on the connection and choose New Query, which will open a new query window on the right side. Start typing the word CREATE and an intellisense drop down will open and one of the choices will be sqlCreateDatabase. Choose that option and a query will be scaffolded with the database name highlighted in the three places that it occurs in the query. You can just start typing the database name “JudgeMyTaste” and it will be replaced in all three places so that the final query looks like this.

-- Create a new database called 'JudgeMyTaste'
-- Connect to the 'master' database to run this snippet
USE master
GO
-- Create the new database if it does not exist already
IF NOT EXISTS (
  SELECT [name]
    FROM sys.databases
    WHERE [name] = N'JudgeMyTaste'
)
CREATE DATABASE JudgeMyTaste
GO

Now you can just click the green Run arrow at the top of the window to create the database. Simple, no?

Now when you expand the Databases folder in the Connection Explorer, you will see the JudgeMyTaste database in the list. Right-click on the new database and choose New Query again. Start typing CREATE again and this time choose sqlCreateTable from the options presented. Again, you can start typing the table name FavoriteBands and it will be filled in all the places it occurs in the query.

You’ll also need to add some other columns to the table. Add the columns for Id, Name, EnteredBy, and EnteredOn so that the query looks like this:

-- Create a new table called '[FavoriteBands]' in schema '[dbo]'
-- Drop the table if it already exists
IF OBJECT_ID('[dbo].[FavoriteBands]', 'U') IS NOT NULL
DROP TABLE [dbo].[FavoriteBands]
GO
-- Create the table in the specified schema
CREATE TABLE [dbo].[FavoriteBands](
  [Id] [int] IDENTITY(1,1) NOT NULL,
  [Name] [varchar](255) NULL,
  [EnteredBy] [varchar](255) NULL,
  [EnteredOn] [date] NULL
);
GO

Then run the query by clicking the green Run arrow as before.

It’s good practice to create a user specifically for your application to connect with the database. One that only has the permissions that it will need to interact with your database. Here’s a script to create a login and a user for the database and assign that user dbo permissions to the database.

USE master

GO

CREATE LOGIN webapp WITH PASSWORD=N'[email protected]!', DEFAULT_DATABASE=JudgeMyTaste

GO

ALTER LOGIN webapp ENABLE

GO

USE JudgeMyTaste

GO

CREATE USER webapp FOR LOGIN webapp
EXEC sp_addrolemember 'db_owner', 'webapp'

GO

It might seem like a lot going on here, but it simply creates a login for SQL Server, makes that login a user for the JudgeMyTaste database, and add it to the db_owner role for the database. This will allow that login to do all the CRUD operations that the application will need. Now your database is ready to be used by your application!

Connect SQL Server to Your ASP.NET Core 2.2 MVC Application

Before anything else, you’ll need the Entity Framework Core NuGet package. To install it, run the following command in the terminal.

dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 2.2.4

Start by adding the connection string to your appsettings.json file in the root of your MVC project, so that it looks like this:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "JudgeMyTasteDatabase": "Server=.;Database=JudgeMyTaste;user id=webapp;[email protected]!"
  }
}

In the Models folder, create a class file called FavoriteBand.cs.

using System;
using System.ComponentModel.DataAnnotations;

namespace JudgeMyTaste.Models
{
  public class FavoriteBand
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public string EnteredBy { get; set; }
    public DateTime EnteredOn { get; set; }
  }
}

This class will be used to work with the FavoriteBand entries.

In the root of the project, create a folder called Data to house the database context for the application. Create a C# file called JudgeMyTasteContext.cs with the following contents:

using JudgeMyTaste.Models;
using Microsoft.EntityFrameworkCore;

namespace JudgeMyTaste.Data
{
  public class JudgeMyTasteContext : DbContext
  {
    public JudgeMyTasteContext(DbContextOptions<JudgeMyTasteContext> options) : base(options)
    {
    }

    public DbSet<FavoriteBand> FavoriteBands { get; set; }
  }
}

In your Startup.cs file, in the ConfigureServices() method, right before the services.AddMvc()... line, add the newly created context with the connection string.

services.AddDbContext<JudgeMyTasteContext>(options => options.UseSqlServer(Configuration.GetConnectionString("JudgeMyTasteDatabase")));

Now your database is all hooked into your application. All you need to do is create some way for the user to enter their favorite bands. To get some more scaffolding goodness for the CLI, install the Code Generation tool.

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design

Now you can scaffold a controller to handle all the CRUD operations for the FavoriteBand class by running the following command from the terminal.

dotnet aspnet-codegenerator controller -name FavoriteBandsController -async -m JudgeMyTaste.Models.FavoriteBand -dc JudgeMyTaste.Data.JudgeMyTasteContext -namespace Controllers -outDir Controllers -udl

This is a long one but if you break it down into its component pieces, it’s easier to understand.

The first part just calls the dotnet CLI’s new aspnet-codegenerator command for a controller. You want the controller’s name to be “FavoriteBandsController” and for the controller actions to all be -async. The model being used to generate the controller is the JudgeMyTaste.Models.FavoriteBand class, and the database context will be the JudgeMyTaste.Data.JudgeMyTasteContext class you just created. The namespace and output directory for the controller will be Controllers and the -udl switch tells the generator to use the default layout for the views it will generate (yeah, it’s going to generate views for everything too!). Pretty cool, right?

Once you run the command, you should see the controller and all it’s views show up. The only thing left is to create a link so that users can get to the favorite bands section of the site easily.

In the Views/Shared folder open the Layout.cshtml file and add a link to the menu to get to the new section of the site.

<li class="nav-item">
  <a class="nav-link text-dark" asp-area="" asp-controller="FavoriteBands" asp-action="Index">Favorite Bands</a>
</li>

Now when you run the application, you can click on the Favorite Bands menu item and see a list of all the favorite bands that have been entered. Of course there aren’t any right now, so add one using the Create New link at the top of the page and see it show up in the listing.

Now it’s a little cumbersome to add the EnteredOn value manually, and the code generator you used can’t know that you can just add that field to the entry as it’s being saved, so change the Create() method of the FavoriteBandController to add it automatically.

// POST: FavoriteBands/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,EnteredBy")] FavoriteBand favoriteBand)
{
  if (ModelState.IsValid)
  {
    favoriteBand.EnteredOn = DateTime.Now;
    _context.Add(favoriteBand);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
  }
  return View(favoriteBand);
}

The only things that have changed is that I removed the EnteredOn field from the Bind statement in the method signature, and I added the value DateTime.Now as the value right before saving it to the database.

Add Authentication to Your ASP.NET Core 2.2 MVC + SQL Server Application

What you have now is okay, but there’s currently no way to keep users from editing other user’s entries. We want to make sure to judge people for their favorite band that they actually entered, right?

No reason to write this yourself. You can easily integrate Okta to handle the authentication for you and easily:

Sign up for a forever-free developer account (or log in if you already have one).

Once you have signed up and logged in, you’ll be taken to your dashboard. Make note of your Org URL in the top right corner.

Click on the Applications menu item at the top, click Add Application, and from the first page of the wizard choose Web and click Next.

On the next screen, change the application name to “Judge My Taste App” and update the Base URIs value and the Login Redirect URIs to reflect to the correct port and the fact that you’re running on the HTTPS scheme.

Then click Done and you’re taken to the application page. On the General Settings tab click Edit and add a URL to the Logout Redirect URIs with a value of <a href="https://localhost:5001/signout/callback" target="_blank">https://localhost:5001/signout/callback</a>. This is where Okta will redirect back to after the logout call. This is handled by the ASP.NET OIDC Middleware.

Configure Your ASP.NET Core 2.2 MVC Application for Authentication

Now you need to tell your application how to use Okta for authentication. The easiest way is to use the ASP.NET SDK from Okta. You can install it from NuGet using the following command:

dotnet add package Okta.AspNetCore --version 1.1.5

Add some configuration values to your appsettings.json file to that the final file looks like this:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "JudgeMyTasteDatabase": "Server=.;Database=JudgeMyTaste;user id=webapp;[email protected]!"
  },
  "Okta": {
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}",
    "OktaDomain": "https://{yourOktaDomain}",
    "PostLogoutRedirectUri": "https://localhost:5001/"
  }
}

This PostLogoutRedirectUri is the URL that the middleware will redirect to once Okta has redirected back to the signout/callback URL. You can use any valid URL in the MVC application. Here, I am just redirecting to the root of the application.

Back in the Startup.cs file, add the following using statements:

using Okta.AspNetCore;
using Microsoft.AspNetCore.Authentication.Cookies;

Then at the very beginning of the ConfigureServices() method add:

var oktaMvcOptions = new OktaMvcOptions();
Configuration.GetSection("Okta").Bind(oktaMvcOptions);
oktaMvcOptions.Scope = new List<string> { "openid", "profile", "email" };
oktaMvcOptions.GetClaimsFromUserInfoEndpoint = true;

services.AddAuthentication(options =>
{
  options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  options.DefaultChallengeScheme = OktaDefaults.MvcAuthenticationScheme;
})
.AddCookie()
.AddOktaMvc(oktaMvcOptions);

This is a pretty dense chunk of code, but most of it is boilerplate for the OIDC middleware that the Okta SDK is built on. The first part just binds all of those configuration values you just added in appsettings.json to the oktaMvcOptions. It also adds the scopes you want to receive (which are the OpenID information, the user’s profile, and the user’s email address). It also tells the middleware that it can get the claims from the user info endpoint, which all OIDC identity providers have.

When the code adds authentication, it tells the OIDC provider to use cookies for storing tokens and that you’ll be sending users to Okta from an MVC application.

To actually wire up authentication, you need to tell the Configure() method to use this service you just configured. Right before the app.UseMvc(...) line, add:

app.UseAuthentication();

Okta is now configured in your application! You still need to set up your application to challenge the user (send them to Okta to authenticate).

Create a new controller in the Controllers folder called AccountController with the following code:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Okta.AspNetCore;

namespace JudgeMyTaste.Controllers
{
  public class AccountController : Controller
  {
    public IActionResult Login()
    {
      if (!HttpContext.User.Identity.IsAuthenticated)
      {
        return Challenge(OktaDefaults.MvcAuthenticationScheme);
      }
      return RedirectToAction("Index", "Home");
    }

    public IActionResult Logout()
    {
      return new SignOutResult(new[]
      {
        OktaDefaults.MvcAuthenticationScheme,
        CookieAuthenticationDefaults.AuthenticationScheme
      });
    }
  }
}

This will give you a Login() and Logout() method to wire up some menu items. Speaking of which, add a new view in Views/Shared called _LoginPartial.cshtml. This will house all the code for the login menu items.

@if (User.Identity.IsAuthenticated)
{
  <ul class="navbar-nav ml-auto">
    <li>
      <span class="navbar-text">Hello, @User.Identity.Name</span> &nbsp;
      <a onclick="document.getElementById('logout_form').submit();" style="cursor: pointer;">Log out</a>
    </li>
  </ul>
  <form asp-controller="Account" asp-action="Logout" method="post" id="logout_form"></form>
}
else
{
  <ul class="navbar-nav">
    <li><a asp-controller="Account" asp-action="Login">Log in</a></li>
  </ul>
}

Change the main menu in Views/Shared/_Layout.cshtml to add this in and move the main menu to the left and have the login menu on the far right. The final div that houses the menu should look like this:

<div class="navbar-collapse collapse justify-content-between">
  <ul class="navbar-nav mr-auto">
    <li class="nav-item">
      <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
    </li>
    <li class="nav-item">
      <a class="nav-link text-dark" asp-area="" asp-controller="FavoriteBands" asp-action="Index">Favorite Bands</a>
    </li>
  </ul>
  <partial name="_LoginPartial" />
</div>

The class list for the navbar-collapse has changed to add the justify-content-between class that will keep the menus apart. The ul’s class also changed to mr-auto which will help keep it left. Lastly, the login partial is added at the end of the menu.

Don’t just sit there, fire this thing up and judge me for liking Nickleback!

Now you have a complete CRUD slice built in an ASP.NET Core 2.2 MVC application saving data to a SQL Server database! Now you can take the same path to add things like favorite movie, favorite food, and favorite beverage so that you can easily and completely judge people for their taste online!!!