cft

How to Koa and React Tutorial Here is a tutorial on Koa.

How to Koa and React Tutorial Here is a tutorial on Koa.


user

projects 123

2 years ago | 16 min read

index.js file
index.js

const {MongoClient} = require("mongodb");

const client = new MongoClient('mongodb://localhost:27017', {

useNewUrlParser: true,

useUnifiedTopology: true

});

client.connect(err => {

if(err){

console.error(err);

process.exit(-1);

}

console.log("Successfully connected to MongoDB");

})

module.exports = client;

index.js file

**index.js**

const {MongoClient} = require("mongodb");

const client = new MongoClient('mongodb://localhost:27017', {

useNewUrlParser: true,

useUnifiedTopology: true

});

client.connect(err => {

if(err){

console.error(err);

process.exit(-1);

}

console.log("Successfully connected to MongoDB");

})

module.exports = client;

**users.dao.js**

const users = require('./index').db('time_table').collection('users');

const ObjectId = require('mongodb').ObjectId;

const save = async (user) => {

const result = await users.insertOne(user);

console.log(result.insertedCount);

return result.insertedCount;

}

const getAll = async () =>{

const cursor = await users.find();

return cursor.toArray();

}

const getById = async (id) =>{

return await users.findOne({_id:ObjectId(id)});

}

const update = async (id, user) =>{

const result = await users.replaceOne({_id:ObjectId(id)}, user);

return result.modifiedCount;

}

const removeById = async id =>{

const result = await users.deleteOne({_id:ObjectId(id)});

return result.deletedCount;

}

module.exports = {getAll,getById,removeById,save,update};

**users.api.js**

const {getAll, getById, removeById, save, update} = require('../dal/users.dao');

const createUser = async ({userId, userName, email, password, userType, other}) => {

const user = {

userId,

userName,

email,

password,

userType,

other

}

return await save(user);

}

const getUsers = async ()=>{

return await getAll();

}

const getUser = async id =>{

return await getById(id);

}

const deleteUser = async id =>{

return await removeById(id);

}

const updateUser = async (id,{userId, userName, email, password, userType, other})=>{

return await update(id,{userId, userName, email, password, userType, other});

}

module.exports = {

createUser,

getUsers,

getUser,

deleteUser,

updateUser

}

**user.routes.js**

const Router = require("@koa/router");

const {createUser, getUser, getUsers,updateUser,deleteUser} = require('../api/users.api');

const router = new Router({

prefix:'/users'

})

router.get('/',async ctx=>{

ctx.body= await getUsers() ;

})

router.post('/',async ctx=>{

let user = ctx.request.body;

user = await createUser(user);

ctx.response.status = 200;

ctx.body = user;

})

router.get('/:id',async ctx=>{

const id = ctx.params.id;

ctx.body = await getUser(id);

})

router.delete('/:id',async ctx=>{

const id = ctx.params.id;

await deleteUser(id);

})

router.put('/:id',async ctx=>{

const id = ctx.params.id;

let user = ctx.request.body;

user = await updateUser(id,user);

ctx.response.status = 200;

ctx.body = user;

})

module.exports = router;

**server.js**

//Import Koa

const Koa = require('Koa');

//Import body-parser

const bodyParser = require('koa-bodyparser');

//Importing the routes

const userRoutes = require('./routes/users.routes');

//Import cors

const cors = require('@koa/cors');

//Start App

const app = new Koa();

//Use cors

app.use(cors());

//Using body parser

app.use(bodyParser());

//Registering the routes

app.use(userRoutes.routes()).use(userRoutes.allowedMethods());

//Setup the port

app.listen(5000);

console.log("Application is running on port 5000");

Here is frontend code.

**REACT**

**Main.jsx**

import React from 'react';

import ReactDOM from 'react-dom/client';

import App from './App';

import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(

<BrowserRouter>

<React.StrictMode>

<App />

</React.StrictMode>

</BrowserRouter>,

);

**index.html**

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<title>My Parcel App</title>

</head>

<body>

<div id="root"></div>

<script type="module" src="Main.jsx"></script>

</body>

</html>

**App.jsx**

import React from "react";

import { Route, Routes } from "react-router-dom";

import Header from "./components/Header";

import AddUser from "./components/Pages/AddUser";

function App() {

return (

<React.Fragment>

<header>

<Header />

</header>

<main>

<Routes>

<Route path="/add" element={<AddUser />} exact />

</Routes>

</main>

</React.Fragment>

);

}

//<Route path="/books/:id" element={<BookDetail />} exact />

export default App;

**AddUser.js**

import axios from "axios";

import React, { useState } from "react";

import { useNavigate } from "react-router-dom";

const AddUser = () => {

const history = useNavigate();

const [inputs, setInputs] = useState({

userId: "",

userName: "",

email: "",

password: "",

userType: "",

other: "",

});

const [checked, setChecked] = useState(false);

const handleChange = (e) => {

setInputs((prevState) => ({

...prevState,

[e.target.name]: e.target.value,

}));

// console.log(e.target.name, "Value", e.target.value);

};

const sendRequest = async () => {

await axios

.post("http://localhost:5000/users", {

userId: String(inputs.userId),

userName: String(inputs.userName),

email: String(inputs.email),

password: Number(inputs.password),

userType: String(inputs.userType),

other: String(inputs.other),

})

.then((res) => res.data);

};

const handleSubmit = (e) => {

e.preventDefault();

console.log(inputs, checked);

sendRequest().then(() => history("/users"));

};

return (

<form onSubmit={handleSubmit}>

<input

type="text"

placeholder="Enter name"

value={inputs.userId}

style={{ margin: 5 }}

name="userId"

onChange={handleChange}

/>

<input

type="text"

placeholder="Enter name"

value={inputs.userName}

style={{ margin: 5 }}

name="userName"

onChange={handleChange}

/>

<input

type="email"

placeholder="Enter name"

value={inputs.email}

style={{ margin: 5 }}

name="email"

onChange={handleChange}

/>

<input

type="password"

placeholder="Enter name"

value={inputs.password}

style={{ margin: 5 }}

name="password"

onChange={handleChange}

/>

<input

type="text"

placeholder="Enter name"

value={inputs.userType}

style={{ margin: 5 }}

name="userType"

onChange={handleChange}

/>

<input

type="text"

placeholder="Enter name"

value={inputs.other}

style={{ margin: 5 }}

name="other"

onChange={handleChange}

/>

<button type="submit" style={{ margin: 5 }}>

Add User

</button>

</form>

);

};

export default AddUser;

**Books.js**

import React, { useEffect, useState } from "react";

import "./Book.css";

import axios from "axios";

import Book from "./Book";

const URL = "http://localhost:5000/books";

const fetchHandler = async () => {

return await axios.get(URL).then((res) => res.data);

};

const Books = () => {

const [books, setBooks] = useState();

useEffect(() => {

fetchHandler().then((data) => setBooks(data.books));

}, []);

console.log(books);

return (

<div>

<ul>

{books &&

books.map((book, i) => (

<li className="book" key={i}>

<Book book={book} />

</li>

))}

</ul>

</div>

)

}

export default Books

**Book.js**

import React from 'react'

import { Button } from "@mui/material";

import axios from "axios";

import { Link, useNavigate } from "react-router-dom";

import "./Book.css";

const Book = (props) => {

const history = useNavigate();

const { _id, name, author, description, price, image } = props.book;

const deleteHandler = async () => {

await axios

.delete(`http://localhost:5000/books/${_id}`)

.then((res) => res.data)

.then(() => history("/"))

.then(() => history("/books"));

};

return (

<div className="card">

<img src={image} alt={name} />

<article>By {author}</article>

<h3>{name}</h3>

<p>{description}</p>

<h3>Rs {price}</h3>

<Button LinkComponent={Link} to={`/books/${_id}`} sx={{ mt: "auto" }}>

Update

</Button>

<Button color="error" onClick={deleteHandler} sx={{ mt: "auto" }}>

Delete

</Button>

</div>

);

}

export default Book

**BookDetail.js**

import {

Box,

Button,

Checkbox,

FormControlLabel,

FormLabel,

TextField,

} from "@mui/material";

import axios from "axios";

import React, { useEffect, useState } from "react";

import { useNavigate, useParams } from "react-router-dom";

const BookDetail = () => {

const [inputs, setInputs] = useState();

const id = useParams().id;

const [checked, setChecked] = useState(false);

const history = useNavigate();

useEffect(() => {

const fetchHandler = async () => {

await axios

.get(`http://localhost:5000/books/${id}`)

.then((res) => res.data)

.then((data) => setInputs(data.book));

};

fetchHandler();

}, [id]);

const sendRequest = async () => {

await axios

.put(`http://localhost:5000/books/${id}`, {

name: String(inputs.name),

author: String(inputs.author),

description: String(inputs.description),

price: Number(inputs.price),

image: String(inputs.image),

available: Boolean(checked),

})

.then((res) => res.data);

};

const handleSubmit = (e) => {

e.preventDefault();

sendRequest().then(() => history("/books"));

};

const handleChange = (e) => {

setInputs((prevState) => ({

...prevState,

[e.target.name]: e.target.value,

}));

};

return (

<div>

{inputs && (

<form onSubmit={handleSubmit}>

<Box

display="flex"

flexDirection="column"

justifyContent={"center"}

maxWidth={700}

alignContent={"center"}

alignSelf="center"

marginLeft={"auto"}

marginRight="auto"

marginTop={10}

>

<FormLabel>Name</FormLabel>

<TextField

value={inputs.name}

onChange={handleChange}

margin="normal"

fullWidth

variant="outlined"

name="name"

/>

<FormLabel>Author</FormLabel>

<TextField

value={inputs.author}

onChange={handleChange}

margin="normal"

fullWidth

variant="outlined"

name="author"

/>

<FormLabel>Description</FormLabel>

<TextField

value={inputs.description}

onChange={handleChange}

margin="normal"

fullWidth

variant="outlined"

name="description"

/>

<FormLabel>Price</FormLabel>

<TextField

value={inputs.price}

onChange={handleChange}

type="number"

margin="normal"

fullWidth

variant="outlined"

name="price"

/>

<FormLabel>Image</FormLabel>

<TextField

value={inputs.image}

onChange={handleChange}

margin="normal"

fullWidth

variant="outlined"

name="image"

/>

<FormControlLabel

control={

<Checkbox

checked={checked}

onChange={() => setChecked(!checked)}

/>

}

label="Available"

/>

<Button variant="contained" type="submit">

Update Book

</Button>

</Box>

</form>

)}

</div>

);

};

export default BookDetail;

Upvote


user
Created by

projects 123


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles