Crud Application using Mern Stack

Step 1:

Initializing package.json

Step 2:

Inside server.js
  • In line 1, we are including the module “express” by using the function require(). We installed this module in step 2 along with some other modules. So when we import the “express” module we basically get returned a function. Now let’s store that function in a constant variable called “express”.
  • Now let’s invoke the function “express” and then store that result in a constant variable called “app”. This app variable is actually an object. So in short, whenever this express function gets called we get an object and in our case we stored that object in a variable called “app”. Now we can use different functions of this object called app like app.use(), app.get(), app.listen()etc, more of which we will see later on.
  • At Line 3 we stored the result from importing the module “cors”. I’ll mention why we need this later on.
  • At Line 4, 5 we are importing the “dotenv” module and by calling the config() function we are basically making sure that we can pull or extract all our existing environment variables from our .env file.
  • At Line 8, we created a variable called Port, which will be equal to the environment variable called port if it has been initialized
  • Now let’s use the app.listen() function to listen to the PORT 5000. And then let’s show the Line “Server running on port 5000” on our console.

Step 3: Connecting our Database

  1. Create a .env dile and then place your copied mongodb uri for connecting to mongoDb via compass into that .env file. We won’t be keeping our .env file because of security issues.
  2. In server.js, we are going to establish a connection to mongoDb using this url from the .env file.
  1. Create a Folder called “models” inside the backend folder and then create a file called “PokemonData.js”.
  2. In “PokemonData.js” we are gonna create our schema in the following way:
Inside PokemonData.js

Explanation:

inside server.js

Step 4: Designing our frontend:

import AddPokemon from './components/AddPokemon';import EditPokemon from './components/EditPokemon';import PokemonTable from './components/PokemonTable';import Navbar from './layouts/Navbar';import Axios from 'axios';import { BrowserRouter as Router, Route, Link } from 'react-router-dom';import './App.css';function App() {function addNewPokemon(Name, Type) {Axios.post('http://localhost:5000/insert', {Name: Name,Type: Type,});alert('New Pokemon Added!');}return (<Router><div className="App"><Navbar></Navbar><Routeexactpath="/"component={() => (<AddPokemon addNewPokemon={addNewPokemon}></AddPokemon>)}></Route><Route exact path="/PokemonTable" component={PokemonTable}></Route><Routepath="/EditPokemon/:id/:name/:type"component={EditPokemon}></Route></div></Router>);}export default App;

Explanation:

<Routepath="/EditPokemon/:id/:name/:type"component={EditPokemon}></Route>
import React, { Component } from 'react';import { Link } from 'react-router-dom';export default class navbar extends Component {render() {return (<div><nav class="navbar navbar-expand-lg navbar-dark bg-primary"><a class="navbar-brand" href="#">POKEMON CRUD</a><buttonclass="navbar-toggler"type="button"data-toggle="collapse"data-target="#navbarColor01"aria-controls="navbarColor01"aria-expanded="false"aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button><div class="collapse navbar-collapse" id="navbarColor01"><ul class="navbar-nav mr-auto"><li class="nav-item active"><Link to="/"><a class="nav-link" href="#">Home<span class="sr-only">(current)</span></a></Link></li><Link to="/PokemonTable"><li class="nav-item"><a class="nav-link" href="#">Pokemon List</a></li></Link></ul></div></nav></div>);}}

Explanation:

import React, { Component } from 'react';export default class AddPokemon extends Component {constructor(props) {super(props);this.state = {Name: '',Type: '',};}render() {return (<div><p>Add New Pokemons!</p><div class="form-group"><label>{' '}Name:<inputonChange={(e) => {this.setState({ Name: e.target.value });}}type="text"name="Name"placeholder="Enter Pokemon Name"></input></label></div><div class="form-group"><label>Type:<selectonChange={(e) => {this.setState({ Type: e.target.value });}}name="type"><option value="grass">Grass</option><option value="electric">Electric</option><option value="water">Water</option><option value="Fire">Fire</option></select></label></div><buttonclass="btn btn-primary"onClick={() => {this.props.addNewPokemon(this.state.Name, this.state.Type);}}>SUBMIT</button></div>);}}

Explanation:

import Axios from 'axios';import React, { useState } from 'react';
function EditPokemon(props) {const name = props.match.params.name;const type = props.match.params.type;const [Name, setName] = useState(name);const [Type, setType] = useState(type);
function editPokemon() {const id = props.match.params.id;alert('Changes updated!');Axios.put('http://localhost:5000/edit/', {id: id,Name: Name,Type: Type,});}return (<div><div class="form-group my-3"><label>{' '}Name:<inputvalue={Name}onChange={(e) => {setName(e.target.value);}}type="text"name="Name"placeholder="Enter Pokemon Name"></input></label></div><div class="form-group"><label>Type:<selectvalue={Type}onChange={(e) => {setType(e.target.value);}}name="type"><option value="grass">Grass</option><option value="electric">Electric</option><option value="water">Water</option><option value="Fire">Fire</option></select></label></div><buttonclass="btn btn-warning"onClick={() => {editPokemon(Name, Type);}}>UPDATE</button></div>);}export default EditPokemon;
Editing Pokemons

Explanation:

import React, { useEffect, useState } from 'react';import { Link } from 'react-router-dom';import Axios from 'axios';function PokemonTable() {const [list, setList] = useState([]);useEffect(() => {Axios.get('http://localhost:5000/show').then((res) => {setList(res.data);});}, [list]);function deletePokemon(id) {alert("ITEM DELETED");Axios.delete(`http://localhost:5000/delete/${id}`);}return (<div><table class="table table-hover"><thead><tr><th scope="col">Type</th><th scope="col">Name</th><th scope="col">Type</th><th scope="col">EDIT</th><th scope="col">DELETE</th></tr></thead><tbody>{list.map((x) => (<tr class="table-active"><th scope="row">Active</th><td>{x.Name}</td><td>{x.Type}</td><td><Link to={`/EditPokemon/${x._id}/${x.Name}/${x.Type}`}><button class="btn btn-warning">EDIT</button>{' '}</Link></td><td><buttononClick={() => {deletePokemon(x._id);}}class="btn btn-danger">DELETE</button></td></tr>))}</tbody></table></div>);}export default PokemonTable;

Explanation:

Step 5: Defining our routes:

app.get('/show', async (req, res) => {await PokemonModel.find({}, (err, result) => {if (!err) res.send(result);});});app.post('/insert', async (req, res) => {const Name = req.body.Name;const Type = req.body.Type;const newPokemon = new PokemonModel({Name: Name,Type: Type,});await newPokemon.save();});app.put('/edit', async (req, res) => {const Name = req.body.Name;const Type = req.body.Type;try {await PokemonModel.findById(req.body.id, (err, newPokemon) => {newPokemon.Name = Name;newPokemon.Type = Type;newPokemon.save();});} catch (err) {console.log(err);}});app.delete('/delete/:id', async (req, res) => {await PokemonModel.findByIdAndRemove(req.params.id).exec();});

Explanation:

--

--

--

A novice developer/programmer on a quest to explore the world of coding and development. It's tough, bumpy and scary. But that doesn't hold this lady back!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Top Reasons Why Your Angular App Is Slow

Create a new NextJS site with Typescript, Material-UI, and Cypress

State of the React JS in 2021

Understanding Asynchronous Requests and Obser vables

images/callback_flow.png

Access the filesystem with React Native and Expo

React Redux Walkthrough — High Level Overview Part 2

Threejs Concepts

npm weekly #96: npm takes over the airwaves on FLOSS Weekly and Front End Happy Hour, plus videos…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Faiza Anan Noor

Faiza Anan Noor

A novice developer/programmer on a quest to explore the world of coding and development. It's tough, bumpy and scary. But that doesn't hold this lady back!

More from Medium

Create Weather App Using React JS , Tailwind CSS, & TypeScript Part 1 — Installation

Sending Notification using LINE Notify API, React and Netlify

How to use the color picker in ReactJS

How to Create a Web App with MySQL, Express and React