Command.execute issue

I will try to explain this the best I can however it is a little confusing. Here is my code for executing a slash command.

    if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction, Servers, Tickets, client);
    } catch (error) {
        console.error(error);
        await interaction.reply({ embeds: [errorEmbed], ephemeral: true });
    }
});

If I put client right before Servers it allows me to use it in other commands however if I put it later such as after Tickets it doesn’t work, this also happens when I move Tickets or Servers to the end I can no longer use those in the commands. Any ideas on why this could be?

how to modify the link color of amchart5 –

enter image description here

The width of the link(line) can be modified, but the color does not change.

I’ve tried many things…

series.links.template.setAll({
      strokeWidth: 2,
      strokeOpacity: 0.5,
      color: am5.color('#ffffff'),
      links: am5.color('#ffffff'),
      link: am5.color('#ffffff'),
      fill: am5.color('#ffffff'),
      strokeColor: am5.color('#ffffff'),
      background: am5.color('#ffffff'),
      backgroundColor: am5.color('#ffffff'),
      stroke: am5.color('#ffffff'),
      templateField: 'nodeSettings',
      configField: {
        fill: am5.color('#ffffff'),
        stroke: am5.color('#ffffff'),
        strokeColor: am5.color('#ffffff'),
      },
      strokeLinejoin: 'round',
    });

help me plz , ,

ECharts Cannot Use Local Image For Graphic

I’m using ECharts v4 https://echarts.apache.org/v4/en/index.html

I have this scatter setup

option = {
    xAxis: {
    },
    yAxis: {
    },
    graphic: {
        type: "image",
        style: {
            image: <IMAGE_PATH>,
            width: 1000,
            height: 1000,
            x: 100,
            y: 100,
        },
    },
    series: [
        {
            symbolSize: 20,
            data: [
                [10.0, 8.04],
                [8.0, 6.95],
                [13.0, 7.58],
                [9.0, 8.81],
                [11.0, 8.33],
                [14.0, 9.96],
                [6.0, 7.24],
                [4.0, 4.26],
                [12.0, 10.84],
                [7.0, 4.82],
                [5.0, 5.68],
            ],
            type: "scatter",
        },
    ],
};

If I use an image url (a random image on Google for example) for <IMAGE_PATH>, this sets a background image for my chart.

However, if I use a full file path that points to an image stored locally for <IMAGE_PATH>, nothing is shown, and there’s no error either.

How can I get this to work for local images?

How to increment only one value in javascript

I want to only increment the score in one box but it gets incremented in 2 places.
my code:

var homescore = document.getElementById('home-score')
var guestscore = document.getElementById('guest-score')

var i = 0; 
function add1() {           
    i++;       
    homescore.innerHTML = i
}

var i = 0
function add2() {
    i += 2
    homescore.innerHTML = i
}


var i = 0
function add3() {
    i += 3
    homescore.innerHTML = i
}

var i = 0; 
function add1g() {           
    i++;       
    guestscore.innerHTML = i
}

var i = 0
function add2g() {
    i += 2
    guestscore.innerHTML = i
}


var i = 0
function add3g() {
    i += 3
    guestscore.innerHTML = i
}


HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BasketBall Score Board</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="left-side">
        <h1 class="left-title">HOME</h1>
        <br />
        <h1 class="home-score" id="home-score">0</h1>
        <button id="add1" onclick="add1()">+1</button>
        <button id="add2" onclick="add2()">+2</button>
        <button id="add3" onclick="add3()">+3</button>
      </div>
      <div class="right-side">
        <h1 class="right-title">GUEST</h1>
        <br />
        <h1 class="guest-score" id="guest-score">0</h1>
        <button id="add1" onclick="add1g()">+1</button>
        <button id="add2" onclick="add2g()">+2</button>
        <button id="add3" onclick="add3g()">+3</button>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

FOr example, if I clicked the +1 button in the home and incremented it to 9. And then after that, I click +1 in guest it shows 10 in the guest.
I want different values for each box. If I click +1 in HOME it should increment to 1 and then if I clicked +1 in guest it should increment to 1 not 2. And If possible tell me a shorter way to write this code. THANKS

React Native: How to wrap content the height of Scrollview?

I’m trying to create a filter button. I need the Scrollview because the categories comes from an API and it wouldn’t fit in a single screen size. I need the height to wrap content because the Scrollview is horozontal but it did not work when I used alignSelf:'baseline'. I could wrap the ScrollView around a View but the button height is not static.

<ScrollView 
    showsHorizontalScrollIndicator={false} 
    horizontal={true} 
    style={[GlobalStyle.ListTab]}>
    {listTab.map(item => (
        <TouchableOpacity key={item.id} 
            activeOpacity={0.8} 
            onPress={() => setStatusFilter(item.name)} 
            style={[GlobalStyle.ButtonTab, status === item.name && GlobalStyle.ActiveButtonTab]}> 
            <Text style={[GlobalStyle.TextTab]}>{item.name}</Text>
        </TouchableOpacity>
    ))}
</ScrollView>

GlobalStyle.js

ListTab: {
    alignSelf:'baseline',
    marginBottom: 20,
},
ButtonTab: {
    minWidth: DEVICE_WIDTH / 3.6,
    flexDirection: 'row',
    padding: 10,
    justifyContent: 'center', 
    backgroundColor: white,
    marginHorizontal: 10, 
    elevation: 10,
},
TextTab: {
    fontSize: 16,
    alignSelf:'baseline', 
},
ActiveButtonTab: {
    backgroundColor: purple,
},

ifDefined is not working in the litElement

The main page

export class GdwcHeading extends LitElement {
static get properties() {
return {
  /**
   * Heading size
   */
  size: { type: String },
  /**
   * Heading level
   */
  level: { type: String },
};

}

render() {

const styles = { fontSize: `var(${this.size})` };
const style = styleMap(styles);
this.size = { fontSize: `var(${this.size})` };
this.sanitizeLevel();
return html` <${unsafeStatic(this.sanitizeLevel(this.level))} 
 style=${style}><slot></slot></${unsafeStatic(
  this.sanitizeLevel(this.level)
)}> `;

}

sanitizeLevel(level) {
switch (this.level) {
  case `h1`:
    this.level = 'h1';
    break;
  case `h3`:
    this.level = 'h3';
    break;
  case `h4`:
    this.level = 'h4';
    break;
  case `h5`:
    this.level = 'h5';
    break;
  case `h6`:
    this.level = 'h6';
    break;
  default:
    this.level = 'h2';
    break;
}
return level;
}
}

The story page

import { html } from 'lit';
import { ifDefined } from 'lit/directives/if-defined.js';
import { controls, themeControls } from '../stories/fixtures/controls.js';
import '../heading.js';
import '../store.js';
import '../provider.js';
import '../stories/components/gdwc-theme.js';
export default {
  title: 'Elements/Heading',
  component: 'Heading',
  description: 'A simple heading component',
  parameters: {
  docs: {
  description: {
    component: 'A generic heading',
  },
  },
  },
  argTypes: {
  defaultSlot: {
  table: {
    category: 'slots',
  },
  },
  size: {
  options: controls.sizes.options,
  control: controls.sizes.control,
  description: controls.sizes.description,
  table: {
    category: 'properties',
  },
  },
  level: {
  options: controls.headingLevels.options,
  control: controls.headingLevels.control,
  description: controls.headingLevels.description,
  table: {
    category: 'properties',
  },
  },
  ...themeControls,
  },
  };

  const Template = args => {
  const { size, defaultSlot, level } = args;
  return html` <gdwc-theme args=${JSON.stringify(args)}>
  <gdwc-heading ${ifDefined(size)} ${ifDefined(level)}
  >${defaultSlot}</gdwc-heading
  >
  </gdwc-theme>`;
  };

  export const Primary = Template.bind({});

  Primary.args = {
  defaultSlot: 'My Custom Heading',
  };

Over here ifDefined should render the level variable. but it is sticking with the ‘h2’ level in the sanitizeLevel function is that any issue in the sanitize level function. Please try to help me out with this. Any ref to the ifDefined function is that https://lit.dev/docs/templates/directives/#ifdefined

Showing php variables in React table

Hello guys i got this php code

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ico";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if($conn){
    $ico = $_POST['ico'];
    //$nazev = $_POST['nazev'];
    $datum = date('Y-m-d');
    if(strlen($ico)< 8 ||strlen($ico) > 8){
        echo ("<script LANGUAGE='JavaScript'> window.alert('Špatně zadané IČO'); window.location.href='http://localhost:3000'; </script>");
        die;
    }
    else{
        $url = "https://wwwinfo.mfcr.cz/cgi-bin/ares/darv_std.cgi?ico=" . $ico;
        $xml = simplexml_load_file($url);
        $xml->registerXPathNamespace("are", "http://wwwinfo.mfcr.cz/ares/xml_doc/schemas/ares/ares_answer/v_1.0.1");
        $xml->registerXPathNamespace("dtt", "http://wwwinfo.mfcr.cz/ares/xml_doc/schemas/ares/ares_answer/v_1.0.1");
        $vypsaniIco = $xml->xpath("//are:ICO");
        $nazev = $xml->xpath("//are:Obchodni_firma");
        $mesto = $xml->xpath("//dtt:Nazev_obce");
        $ulice = $xml->xpath("//dtt:Nazev_ulice");
        $cisloDomovni = $xml->xpath("//dtt:Cislo_domovni");
        $cisloOrientacni = $xml->xpath("//dtt:Cislo_orientacni");
        }
    }

and i need to get some of variables (for example $vypsaniIco, $nazev) in react table, but i have absolutely dont have idea how to do it, can someone help me please, i got this table in react, the php file where i need to get data has path “http://localhost:80/ico/index.php” and i need to get it directly not from database

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


    return (
        <div className="row">
                <table class="table table-striped table-dark">
                    <thead className='thead-dark'>
                    <tr>
                    <th scope="col">ID</th>
                    <th scope="col">IČO</th>
                    <th scope="col">Název</th>
                    <th scope="col">Město</th>
                    <th scope="col">Ulice</th>
                    <th scope="col">Číslo Domovní</th>
                    <th scope="col">Číslo Orientační</th>
                    <th scope="col">Datum uložení</th>
                    </tr>
                    </thead>
                    <tbody>
                        {
                            item.map(item=>(
                                <tr key={item.ID}>
                                    <td>{item.ID}</td>
                                    <td>{item.ico}</td>
                                    <td>{item.nazev}</td>
                                    <td>{item.mesto}</td>
                                    <td>{item.ulice}</td>
                                    <td>{item.cisloDomovni}</td>
                                    <td>{item.cisloOrientacni}</td>
                                    <td>{item.datum}</td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
        </div>
    );
}

export default Data;

C# MVC JavaScript function for onclick is not working [duplicate]

I was trying to do an ajax callback function, to show the partial view after I click the button ‘Click Me’.

But it keeps showing this error:

enter image description here

Uncaught ReferenceError:
showCount is not defined at HTMLAnchorElement.onclick

I am not sure why even though I have already called the onclick function in the script and controller.

Here are my codes:

cshtml

@using StiWebsite.Models;
@using System.Security.Policy
@model dynamic

@{
    ViewData["Title"] = "Experiential";
}
<table class="table-bordered table-responsive">
    <tr>
        <th>country</th>
        @foreach (StudyTourImgPackage stp in Model.studyImgPackL)
        {
        <tr id="[email protected]">
            <td>@stp.CountryName</td>
            <td><a class="btn btn-danger" onclick="showCount('@stp.CountryID')">Click me</a></td>
        </tr>
        }
    </tr>
</table>
<div class="card" id="workMan" style="hidden">
    <div class="card-body" id="workChild"></div>
</div>

script

@section Scripts {
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/jscript">

    $(document).ready(function() {
    function showCount(countryID) {
        $.ajax({
            type:"POST",
            url="/Experiential/showCount",
            data: { CountryID: countryID },
            success: function (response) {
                $("#workChild").html(response);
                $("#workMan").removeClass('hidden');
                $("#workMan").addClass('active');
            }
        })
    }});
</script>
}

controller

using Microsoft.AspNetCore.Mvc;
using StiWebsite.Data;
using StiWebsite.Models;
using System.Dynamic;

namespace StiWebsite.Controllers
{
    public class ExperientialController : Controller
    {
        private ApplicationDbContext _db;
        public ExperientialController(ApplicationDbContext db)
        {
            _db = db;
        }
        
        [HttpPost]
        public ActionResult showCount(string CountryID)
        {
            return PartialView("_partialTest");
        }
    }
}

Simple Koa and React

Frontend

package.json

[enter image description here][1]

.env

BASE_URL=http://localhost:8000

index.jsx

import React from ‘react’;

import {render} from ‘react-dom’;

import App from ‘./App’;

render(, document.getElementById(‘app’));

index.html

<head>

    <meta charset="UTF 8">

    <title> Post App  </title>

</head>
<div id="app"></div>

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

App.jsx

import React from “react”;

import { BrowserRouter as Router, Routes, Route } from “react-router-dom”;

import Course from “./src/pages/Course”;

import Home from “./src/pages/Home”;

import Student from “./src/pages/Student”;

const App = () => {

return (

<div>

  <Router>

    <Routes>

      <Route path="/" element={<Home/>} />

      <Route path="/course" element={<Course/>}/>

      <Route path="/student" element={<Student/>}/>

    </Routes>

  </Router>

</div>

);

};

export default App;

Student.jsx

import React, { useEffect, useState } from “react”;

import axios from “axios”;

const Student = () => {

const [name, setName] = useState(“”);

const [nic, setNIC] = useState(“”);

const [age, setAge] = useState(“”);

const [courseId, setCourseId] = useState(“”);

const [students, setStudents] = useState([]);

const [courses, setCourses] = useState([]);

const [isEditClick, setIsEditClick] = useState(false);

const [editName, setEditName] = useState(“”);

const [editNIC, setEditNIC] = useState(“”);

const [editAge, setEditAge] = useState(“”);

const [editCourseId, setEditCourseId] = useState(“”);

const [editStudentId, setEditStudentId] = useState(“”);

useEffect(() => {

axios.get(`${process.env.BASE_URL}/course/`).then((res) => {

  setCourses(res.data);

});

axios.get(`${process.env.BASE_URL}/student/`).then((res) => {

  setStudents(res.data);

});

}, []);

const addStudent = (e) => {

e.preventDefault();

const studentObj = {

    name,
    nic,
    age,
    courseId
  };

  axios
    .post(`${process.env.BASE_URL}/student/add`, studentObj)
    .then((res) => {
      alert("Data added");

      axios.get(`${process.env.BASE_URL}/student/`).then((res) => {
        setStudents(res.data);

      });

      setName("");

      setNIC("");

      setAge("");

      setCourseId("");
    })
    .catch((err) => {
      alert(err.message);

    });

};

const updateStudent = (e) => {
e.preventDefault();

const studentObj = {

    name: editName,
    nic: editNIC,
    age: editAge,
    courseId: editCourseId
  };

  console.log(studentObj);

  axios
    .put(`${process.env.BASE_URL}/student/${editStudentId}`, studentObj)
    .then((res) => {
      alert("Student Updated");

      axios.get(`${process.env.BASE_URL}/student/`).then((res) => {
        setStudents(res.data);

      });

      setIsEditClick(false);

    })
    .catch((err) => {
      alert(err.message);

    });

};

const deleteStudent = (e) => {

e.preventDefault();

axios
  .delete(`${process.env.BASE_URL}/student/${e.target.id}`)
  .then(() => {
    axios.get(`${process.env.BASE_URL}/student/`).then((res) => {
        setStudents(res.data);

    });

  })
  .catch((err) => {
    alert(err.message);

  });

};

const onEditClick = (e) => {
e.preventDefault();

setEditStudentId(e.target.id);

setIsEditClick(!isEditClick);

const student = students.find((student) => {
  student._id === e.target.id;

});

if (student) {
  setEditName(student.name);

  setEditAge(student.age);

  setEditNIC(student.nic);

  setCourseId(student.courseId);

  setIsEditClick(true);

}

};

return (

<div>

  <h1>Student Page</h1>

  <div style={{ marginBottom: 5 }}>

    <input
      type="text"
      placeholder="Enter name"
      value={name}
      style={{ margin: 5 }}
      onChange={(e) => setName(e.target.value)}
    />

    <input
      type="text"
      placeholder="Enter nic"
      value={nic}
      style={{ margin: 5 }}
      onChange={(e) => setNIC(e.target.value)}
    />

    <input
      type="number"
      placeholder="Enter age"
      value={age}
      style={{ margin: 5 }}
      onChange={(e) => setAge(e.target.value)}
    />

    <select onChange={(e) => setCourseId(e.target.value)}>

      {courses &&
        courses.length > 0 &&
        courses.map((course, index) => (
          <option value={course._id} key={index}>
            {course.courseName}
          </option>

        ))}

    </select>

    <button onClick={(e) => addStudent(e)} style={{ margin: 5 }}>
      Submit
    </button>

  </div>

  <table>

    <tr>

      <th>Name</th>
      <th>NIC</th>
      <th>Age</th>
      <th>Course</th> 
      <th>Actions</th>

    </tr>

    {students &&
      students.length > 0 &&
      students.map((student, index) => (

        <tr key={index}>
          {/* <td>{student.name}</td>

          <td>{student.nic}</td>
          <td>{student.age}</td>
          <td>{student.courseId && student.courseId.courseName}</td> */}

           <td>

              {isEditClick && student._id === editStudentId ? (
                <input
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                />

              ) : (
                student.name
              )}
            </td>

            <td>
              {isEditClick && student._id === editStudentId ? (
                <input
                  type="text"
                  value={editNIC}
                  onChange={(e) => setEditNIC(e.target.value)}
                />

              ) : (
                student.nic
              )}
            </td>

            <td>
              {isEditClick && student._id === editStudentId ? (
                <input
                  type="number"
                  value={editAge}
                  onChange={(e) => setEditAge(e.target.value)}
                />

              ) : (
                student.age
              )}
            </td>

            <td>
              {isEditClick && student._id === editStudentId ? (
                <input
                  type="text"
                  value={editCourseId}
                  onChange={(e) => setEditCourseId(e.target.value)}
                />

              ) : (
                student.courseId
              )}
            </td>

            <td>

              <button id={student._id} onClick={(e) => onEditClick(e)}>
                {isEditClick && student._id === editStudentId ? "Cancel" : "Update"}
              </button>

              {isEditClick && student._id === editStudentId && (
                <button onClick={(e) => updateStudent(e)}>Save</button>
              )}

              <button id={student._id} onClick={(e) => deleteStudent(e)}>
                Delete
              </button>

            </td>

          </tr>

        ))}

  </table>

</div>

);

};

export default Student;

Course.jsx

import React, { useEffect, useState } from “react”;

import axios from “axios”;

const Course = () => {

const [courseName, setCourseName] = useState(“”);

const [courseFee, setCourseFee] = useState(“”);

const [courses, setCourses] = useState([]);

const [isEditClick, setIsEditClick] = useState(false);

const [editId, setEditId] = useState(“”);

const [editName, setEditName] = useState(“”);

const [editFee, setEditFee] = useState(“”);

useEffect(() => {

axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
  setCourses(res.data);

});

}, []);

const saveData = (e) => {
e.preventDefault();

const courseObj = {
  courseName,
  courseFee,
};

axios
  .post(`${process.env.BASE_URL}/course/add`, courseObj)
  .then((res) => {
    alert("Data added");

    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
      setCourses(res.data);

    });

    setCourseName("");

    setCourseFee("");

  })
  .catch((err) => {
    alert(err.message);

  });

};

const updateData = (e) => {
e.preventDefault();

const courseObj = {
  courseName: editName,
  courseFee: editFee,
};

console.log(courseObj);

axios
  .put(`${process.env.BASE_URL}/course/${editId}`, courseObj)
  .then((res) => {
    alert("Course Updated");

    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
      setCourses(res.data);

    });

    setIsEditClick(false);

  })
  .catch((err) => {
    alert(err.message);

  });

};

const deleteCourse = (e) => {
e.preventDefault();

axios
  .delete(`${process.env.BASE_URL}/course/${e.target.id}`)
  .then(() => {
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
      setCourses(res.data);

    });

  })
  .catch((err) => {
    alert(err.message);

  });

};

const onEditClick = (e) => {
e.preventDefault();

setEditId(e.target.id);

setIsEditClick(!isEditClick);

const course = courses.find((course) => course._id === e.target.id);

setEditName(course.courseName);

setEditFee(course.courseFee);

};

return (

<div>

  <h1>Course Page</h1>

  <div>

    <input
      type="text"
      placeholder="Enter course name"
      value={courseName}
      style={{ margin: 5 }}
      onChange={(e) => setCourseName(e.target.value)}
    />

    <input
      type="number"
      placeholder="Enter course free"
      value={courseFee}
      style={{ margin: 5 }}
      onChange={(e) => setCourseFee(e.target.value)}
    />

    <button onClick={(e) => saveData(e)} style={{ margin: 5 }}>
      Submit
    </button>

    <br />

    <table>

      <tr>

        <th>Course Name</th>
        <th>Course Fee</th>
        <th>Actions</th>

      </tr>

      {courses &&
        courses.length > 0 &&
        courses.map((course, index) => (

          <tr key={index}>

            <td>

              {isEditClick && course._id === editId ? (

                <input
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                />

              ) : (
                course.courseName
              )}

            </td>

            <td>

              {isEditClick && course._id === editId ? (

                <input
                  type="number"
                  value={editFee}
                  onChange={(e) => setEditFee(e.target.value)}
                />

              ) : (
                course.courseFee
              )}

            </td>

            <td>

              <button id={course._id} onClick={(e) => onEditClick(e)}>
                {isEditClick && course._id === editId ? "Cancel" : "Update"}
              </button>

              {isEditClick && course._id === editId && (

                <button onClick={(e) => updateData(e)}>Save</button>

              )}

              <button id={course._id} onClick={(e) => deleteCourse(e)}>
                Delete
              </button>

            </td>

          </tr>

        ))}

    </table>

  </div>

</div>

);

};

export default Course;

Home.jsx

import React from “react”;

import { Link } from “react-router-dom”;

const Home = () => {

return (

<div>

  <Link to="student">

    <button>Manage Students</button>

  </Link>

  <Link to="course">

    <button>Manage Courses</button>
  </Link>

</div>

);

};

export default Home;

Unable to show success or error message in nextjs

i am working in nextjs,and i am trying to use api via axios,Api is working fine but unable
to display “message” (success or failure) in web page,In my console showing “success” but not displaying on web
Here is my code

const subscribeMe = async (event) => {
            const emails = email;
            event.preventDefault();
            const res = await fetch('https://myurl.com/admin-panel/Api/subscribe?email='+emails);
            const { error, message } = await res.json();
            if (error) {
                    console.log('error);
                    setError(error);
            } else {
                    console.log('two');
                    setSuccess(message);
            }
};

For display “Success” or “Error” message i am using following code (after submit button of newsletter form),Where i am wrong ?

{success 
? 
<span className="flex items-center text-sm font-bold text-green-700"> 
{success}
</span> 
: 
<span className="flex items-center text-sm font-bold text-red-800">
{error} 
</span>

This code is not working. what is the error of this code

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.   koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.

oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. oa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.

   //Backend
   // index.js
    require("dotenv").config();
    const Koa = require("koa");
    const KoaRouter = require("koa-router");
    const cors = require("@koa/cors");
    const bodyParser = require("koa-bodyparser");
    const json = require("koa-json");
    
    const { dbConnect } = require("./utils/dbConnect");
    
    const courseRoutes = require("./routes/course.routes");
    const studentRoutes = require("./routes/student.routes") ;
    const teacherRoutes = require("./routes/teacher.routes");
    
    const app = new Koa();
    const router = new KoaRouter();
    
    app.use(cors());
    app.use(bodyParser());
    app.use(json());
    
    app.use(router.routes()).use(router.allowedMethods());
    
    app.use(courseRoutes.routes());
    app.use(studentRoutes.routes());
    app.use(teacherRoutes.routes());
    
    router.get("/", (ctx) => {
    ctx.body = {
    message : "student management API"
    }
    });
    
    app.listen(9000, () => {
    dbConnect();
    console.log(`Server is up and running on http://localhost:9000`);
    });
    //dbConnect.js
    
    const mongoose = require("mongoose");
    
    const dbConnect = () => {
    const dbConStr = process.env.MONGODB_URL;
    
    mongoose.connect(dbConStr, () => {
    console.log("__Database connected__");
    });
    };
    module.exports = { dbConnect };
    
.env
    
    // MONGODB_URL = mongodb://localhost:27017/managementdb
    //MONGODB_URL = mongodb+srv://s------:[email protected]/sp1_db?retryWrites=true&w=majority
    
    //model
    //course.model.js
    
    const mongoose = require("mongoose");
    
    const CourseSchema = new mongoose.Schema({
    
    courseName : {
    type: String,
    required: true
    },
    
    courseFee : {
    type: String,
    required: true
    },
    
    students : [{
    type: mongoose.Schema.Types.ObjectId,
    required: false,
    ref: "students"
    }],
    });
    
    const Course = mongoose.model("courses", CourseSchema);
    module.exports = Course;
    //student.model.js
    const mongoose = require("mongoose");
    
    const StudentSchema = new mongoose.Schema({
    name : {
    type: String,
    required: true
    },
    
    nic : {
    type: String,
    required: true
    },
    
    age : {
    type: Number,
    required: true
    },
    
    courseId : {
    type: mongoose.Schema.Types.ObjectId,
    required: false,
    ref: "courses"
    },
    });
    const Student = mongoose.model("students", StudentSchema);
    module.exports = Student;
    //teacher.model.js
    const mongoose = require("mongoose");
    
    const TeacherSchema = new mongoose.Schema({
    name: {
    type: String,
    required: true
    },
    
    salary: {
    type: Number,
    required: true
    }
    })
    const Teacher = mongoose.model("teachers", TeacherSchema);
    module.exports = Teacher;
    
    //controller
    //course.controller.js
    
    const Course = require("../models/course.model");
    const addCourese = async (ctx) => {
    try{
    const { courseName, courseFee, students } = ctx.request.body;
    
    const course = await Course.create({
    courseName: courseName,
    courseFee: courseFee,
    students: students,
    });
    return (ctx.body = course );
    }catch(error) {
    return (ctx.body = { message: error.message });
    }
    };
    
    const getCourse = async (ctx) => {
    try {
    const courses = await Course.find().populate({
    path: "students",
    select: "name nic age",
    });
    return (ctx.body = courses );
    } catch (error) {
    return (ctx.body = { message: error.message });
    }
    };
    
    const updateCourse = async (ctx) => {
    try {
    const courseId = ctx.params.courseId;
    const { courseName, courseFee, students } = ctx.request.body;
    const course = await Course.findByIdAndUpdate(courseId, {
    courseName: courseName,
    courseFee: courseFee,
    students: students,
    });
    return (ctx.body = course);
    } catch (error) {
    return (ctx.body = { message: error.message });
    }
    };
    
    const deleteCourse = async (ctx) => {
    try {
    const courseId = ctx.params.courseId;
    const course = await Course.findByIdAndDelete(courseId);
    return (ctx.body = course);
    }catch (error) {
    return (ctx.body = { message: error.message });
    }
    }
    module.exports = {
    addCourese, getCourse, updateCourse,deleteCourse,
    };
    student.controller.js
    const Student = require("../models/student.model");
    const Course = require("../models/course.model");
    
    const addStudents = async (ctx) => {
    try {
    const { name, nic, age, courseId } = ctx.request.body;
    const student = await Student. create ({
    name, nic, age, courseId });
    await Course.findByIdAndUpdate(courseId, {$push: { students: student._id } });
    return (ctx.body = student);
    } catch(error) {
    return (ctx.body = { message : error.message });
    }
    };
    
    const getStudents = async (ctx) => {
    try {
    const students = await Student.find().populate({
    path: "courseId",
    select: "courseName courseFee",
    });
    return (ctx.body = students);
    } catch (error) {
    return (ctx.body = { message: error.message });
    }
    };
    
    const updateStudent = async (ctx) => {
    try {
    const studentId = ctx.params.studentId;
    const { name, nic, age, courseId } = ctx.request.body;
    
    const student = await Student.findByIdAndUpdate(studentId, {
    name, nic, age, courseId, });
    await Course.findByIdAndUpdate(student.courseId, {
    $pull: { students: studentId },
    });
    await Course.findByIdAndUpdate(courseId, {
    $push: {students: studentId },
    });
    return (ctx.body = { message: error.message });
    } catch (error) {
    return (ctx.body = { message: error.message });
    }
    };
    
    const deleteStudent = async (ctx) => {
    try {
    const studentId = ctx.params.studentId;
    const student = await student.findById(studentId);
    await Course.findByIdAndUpdate(student.courseId, {
    $pull: { students: studentId }
    });
    await Student.findByIdAndDelete(studentId);
    return (ctx.body = student);
    }catch (error) {
    return (ctx.body = { message: error.message });
    }
    };
    module.exports = {
    addStudents, getStudents, updateStudent, deleteStudent,
    };
    
    teacher.controller.js
    const Teacher = require("../models/teacher.model");
    
    const addTeacher = async (ctx) => {
    try{
    const { name, salary } = ctx.request.body;
    const teacher = await Teacher.create({
    name, salary, });
    return (ctx.body = teacher);
    } catch (error){
    return (ctx.body = { message: error.message });
    }
    };
    
    const getTeachers = async (ctx) => {
    try {
    const teachers = await Teacher.find({});
    return (ctx.body = teachers );
    } catch (error) {
    return (ctx.body = { message: error.message });
    }
    };
    
    const editTeacher = async (ctx) => {
    try {
    const teacherId = ctx.params.teacherId;
    const { name, salary } = ctx.request.body;
    const teacher = await Teacher.findByIdAndUpdate(teacherId, {
    name, salary, });
    return (ctx.body = teacher);
    } catch (error) {
    return (ctx.body = { message: error.message });
    }
    };
    
    const deleteTeacher = async (ctx) => {
    try{
    const teacherId = ctx.params.teacherId;
    const teacher = await Teacher.findByIdAndDelete(teacherId);
    return (ctx.body = teacher);
    }catch (error) {
    return (ctx.body = { message: error.message });
    }
    }
    module.exports = {
    addTeacher, getTeachers, editTeacher, deleteTeacher,
    };
    routes
    course.routes.js
    const koaRouter = require("koa-router");
    const router = new koaRouter({ prefix: "/course" });
    
    const { addCourese, getCourse, updateCourse, deleteCourse } = require("../controller/course.controller");
    
    router.post("/add", addCourese);
    router.delete("/:courseId", deleteCourse);
    router.put("/:courseId", updateCourse);
    router.get("/", getCourse);
    
    module.exports = router;
    
    
    student.routes.js
    const koaRouter = require("koa-router");
    const router = new koaRouter({ prefix: "/student" })
    
    const { addStudents, getStudents, deleteStudent, updateStudent } = require("../controller/student.controller");
    
    router.post("/add", addStudents);
    router.delete("/:studentId", deleteStudent);
    router.put("/:studentId", updateStudent);
    router.get("/", getStudents);
    
    module.exports = router;
    
    teacher.routes.js
    const KoaRouter = require("koa-router");
    const router = new KoaRouter({prefix: "/teacher"});
    
    const { addTeacher, getTeachers, editTeacher, deleteTeacher }=require("../controller/teacher.controller");
    
    router.post("/add", addTeacher);
    router.put("/:teacherId", editTeacher);
    router.delete("/:teacherId", deleteTeacher);
    router.get("/", getTeachers);
    
    module.exports = router;
    ======================================================================================================================
 Frontend
    Course.js
    import React, { useEffect, useState } from "react";
    import axios from "axios";
    const CoursePage = () => {
    const [courseName, setCourseName] = useState("");
    const [courseFee, setCourseFee] = useState("");
    const [courses, setCourses] = useState([]);
    const [isEditClick, setIsEditClick] = useState(false);
    const [editId, setEditId] = useState("");
    
    const [editName, setEditName] = useState("");
    const [editFee, setEditFee] = useState("");
    useEffect(() => {
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
    setCourses(res.data);
    });
    }, []);
    
    const saveData = (e) => {
    e.preventDefault();
    const courseObj = {
    courseName,
    courseFee,
    };
    
    axios .post(`${process.env.BASE_URL}/course/add`, courseObj) .then((res) => {
    alert("Data added");
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
    setCourses(res.data);
    });
    setCourseName("");
    setCourseFee("");
    })
    .catch((err) => {
    alert(err.message);
    });
    };
    
    const updateData = (e) => {
    e.preventDefault();
    const courseObj = {
    courseName: editName,
    courseFee: editFee,
    };
    console.log(courseObj);
    
    axios
    .put(`${process.env.BASE_URL}/course/${editId}`, courseObj)
    .then((res) => {
    alert("Course Updated");
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
    setCourses(res.data);
    });
    setIsEditClick(false);
    })
    .catch((err) => {
    alert(err.message);
    });
    };
    
    const deleteCourse = (e) => {
    e.preventDefault();
    axios
    .delete(`${process.env.BASE_URL}/course/${e.target.id}`)
    .then(() => {
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
    setCourses(res.data);
    });
    })
    .catch((err) => {
    alert(err.message);
    });
    };
    
    const onEditClick = (e) => {
    e.preventDefault();
    setEditId(e.target.id);
    setIsEditClick(!isEditClick);
    
    const course = courses.find((course) => course._id === e.target.id);
    setEditName(course.courseName);
    setEditFee(course.courseFee);
    };
    
    return (
    <div>
    <h1>Course Page</h1>
    <div>
    <input
    type="text"
    placeholder="Enter course name"
    value={courseName}
    style={{ margin: 5 }}
    onChange={(e) => setCourseName(e.target.value)}
    />
    
    <input
    type="number"
    placeholder="Enter course free"
    value={courseFee}
    style={{ margin: 5 }}
    onChange={(e) => setCourseFee(e.target.value)}
    />
    <button onClick={(e) => saveData(e)} style={{ margin: 5 }}>
    Submit
    </button>
    <br />
    
    <table>
    <tr>
    <th>Course Name</th>
    <th>Course Fee</th>
    <th>Actions</th>
    </tr>
    {courses &&
    courses.length > 0 &&
    courses.map((course, index) => (
    <tr key={index}>
    <td>
    {isEditClick && course._id === editId ? (
    <input
    type="text"
    value={editName}
    onChange={(e) => setEditName(e.target.value)}
    />
    ) : (
    course.courseName
    )}
    </td>
    <td>
    {isEditClick && course._id === editId ? (
    <input
    type="number"
    value={editFee}
    onChange={(e) => setEditFee(e.target.value)}
    />
    ) : (
    course.courseFee
    )}
    </td>
    
    <td>
    <button id={course._id} onClick={(e) => onEditClick(e)}>
    {isEditClick && course._id === editId ? "Cancel" : "Update"}
    </button>
    
    {isEditClick && course._id === editId && (
    <button onClick={(e) => updateData(e)}>Save</button>
    )}
    <button id={course._id} onClick={(e) => deleteCourse(e)}>
    Delete
    </button>
    </td>
    </tr>
    ))}
    </table>
    </div>
    </div>
    );
    };
    export default CoursePage;
    
    Student.js
    import React, { useEffect, useState } from "react";
    import axios from "axios";
    
    const StudentPage = () => {
    
    const [name, setName] = useState("");
    const [nic, setNIC] = useState("");
    const [age, setAge] = useState("");
    const [courseId, setCourseId] = useState("");
    
    const [students, setStudents] = useState([]);
    const [courses, setCourses] = useState([]);
    
    const [isEditClick, setIsEditClick] = useState(false);
    const [editName, setEditName] = useState("");
    const [editNIC, setEditNIC] = useState("");
    const [editAge, setEditAge] = useState("");
    const [editCourseId, setEditCourseId] = useState("");
    
    useEffect(() => {
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
    setCourses(res.data);
    });
    axios.get(`${process.env.BASE_URL}/student/`).then((res) => {
    setStudents(res.data);
    });
    }, []);
    
    const addStudent = (e) => {
    e.preventDefault();
    const studentObj = {
    name, nic, age, courseId, };
    
    axios
    .post(`${process.env.BASE_URL}/student/add`, studentObj)
    .then((res) => {
    alert("Data added");
    axios.get(`${process.env.BASE_URL}/student/`).then((res) => {
    setStudents(res.data);
    });
    setName("");
    setNIC("");
    setAge("");
    setCourseId("");
    })
    .catch((err) => {
    alert(err.message);
    });
    };
    
    const updateStudent = (e) => {
    e.preventDefault();
    };
    
    const deleteStudent = (e) => {
    e.preventDefault();
    axios
    .delete(`${process.env.BASE_URL}/student/${e.target.id}`)
    .then(() => {
    axios.get(`${process.env.BASE_URL}/student/`).then((res) => {
    setStudents(res.data);
    });
    })
    .catch((err) => {
    alert(err.message);
    });
    };
    
    const onEditClick = (e) => {
    e.preventDefault();
    const student = students.find((student) => {
    student._id === e.target.id;
    });
    if (student) {
    setEditName(student.name);
    setEditAge(student.age);
    setEditNIC(student.nic);
    setIsEditClick(true);
    }
    };
    
    return (
    <div>
    <h1>Student Page</h1>
    <div style={{ marginBottom: 5 }}>
    <input
    type="text"
    placeholder="Enter name"
    value={name}
    style={{ margin: 5 }}
    onChange={(e) => setName(e.target.value)}
    />
    
    <input
    type="text"
    placeholder="Enter nic"
    value={nic}
    style={{ margin: 5 }}
    onChange={(e) => setNIC(e.target.value)}
    />
    
    <input
    type="number"
    placeholder="Enter age"
    value={age}
    style={{ margin: 5 }}
    onChange={(e) => setAge(e.target.value)}
    />
    
    <select onChange={(e) => setCourseId(e.target.value)}>
    {courses &&
    courses.length > 0 &&
    courses.map((course, index) => (
    <option value={course._id} key={index}>
    {course.courseName}
    </option>
    ))}
    </select>
    <button onClick={(e) => addStudent(e)} style={{ margin: 5 }}>
    Submit
    </button>
    </div>
    
    <table>
    <tr>
    <th>Name</th>
    <th>NIC</th>
    <th>Age</th>
    <th>Course</th>
    <th>Actions</th>
    </tr>
    
    {students &&
    students.length > 0 &&
    students.map((student, index) => (
    <tr key={index}>
    <td>{student.name}</td>
    <td>{student.nic}</td>
    <td>{student.age}</td>
    <td>{student.courseId && student.courseId.courseName}</td>
    {/* -------ACTIONS---------- */} <td>
    <button id={student._id} onClick={(e) => onEditClick(e)}>
    {isEditClick && student._id === editId ? "Cancel" : "Update"}
    </button>
    
    {isEditClick && student._id === editId && (
    <button onClick={(e) => updateData(e)}>Save</button>
    )}
    
    <button id={student._id} onClick={(e) => deleteStudent(e)}>
    Delete
    </button>
    </td>
    {/* ------------------------ */}
    </tr>
    ))}
    </table>
    </div>
    );
    };
    export default StudentPage;
    
AddTeacher.js
    import React, { useEffect, useState } from "react";
    import axios from "axios";
    
    const AddTeacher = () => {
    
    const [name, setname,] = useState("");
    const [salary, setsalary,] = useState("");
    
    const sendData = (e) => {
    e.preventDefault();
    const newTeacher ={
    name, salary, };
    
    axios.post("http://localhost:9000/teacher/add", newTeacher).then(()=>{
    alert("Teacher Added");
    }).catch((err)=>{
    alert(err)
    })
    }
    
    return(
    <div >
    <h2>
    Add Teachers
    </h2>
    
    <form onSubmit={sendData} >
    <div>
    <label htmlFor="name">Name </label>
    <input type="text" id="name" required
    onChange = {(e) => {
    setname(e.target.value);
    }}
    />
    
    </div>
    <div>
    <label htmlFor="name">Salary </label>
    <input type="text" id="salary" required
    onChange = {(e) => {
    setsalary(e.target.value);
    }}
    />
    </div>
    
    <button type="submit" id = "#">Add</button>
    </form>
    </div>
    )
    }
    export default AddTeacher;
    
    ViewTeacher.js
    import React, { useEffect, useState } from "react";
    import axios from "axios";
    
    const ViewTacher =()=> {
    
    const [Teacher, setTeacher] = useState([]);
    
    useEffect(() => {
    axios.get(`http://localhost:9000/teacher/`)
    .then((response) => {
    setTeacher(response.data);
    })
    }, [])
    const deleteTeacher = (e) => {
    e.preventDefault();
    axios
    .delete(`http://localhost:9000/teacher/${e.target.id}`)
    .then(() => {
    axios.get(`http://localhost:9000/teacher/`).then((res) => {
    setTeacher(res.data);
    });
    })
    .catch((err) => {
    alert(err.message);
    });
    };
    
    return (
    <div>
    <h1>All Teacher</h1>
    
    <table>
    <thead>
    <tr>
    <th>Name</th>
    <th>Salary</th>
    </tr>
    </thead>
    <tbody>
    {Teacher.map((teacher)=>{
    return <tr>
    <td>{teacher.name}</td>
    <td>{teacher.salary}</td>
    <td>
    <button id={teacher._id} onClick={(e) => deleteTeacher(e)}>
    
    Delete
    </button>
    </td>
    </tr>
    })}
    </tbody>
    </table>
    </div>
    );
    }
    export default ViewTacher;
    
Home.js
    import React from "react";
    import { Link } from "react-router-dom";
    
    const Home = () => {
    return (
    <div>
    
    <Link to="student">
    <button>Manage Students</button>
    </Link>
    
    <Link to="course">
    <button>Manage Courses</button>
    </Link>
    
    <Link to="addteacher">
    <button>Manage Teacher</button>
    </Link>
    
    <Link to="viewteacher">
    <button>View Teachers</button>
    </Link>
    
    </div>
    );
    };
    export default Home;
    
App.js

    import React from "react";
    import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
    import AddTeacher from "./pages/AddTeacher";
    import CoursePage from "./pages/Course";
    import Home from "./pages/Home";
    import StudentPage from "./pages/Student";
    import ViewTacher from "./pages/ViewTeacher";
    const App = () => {
    return (
    <div>
    <Router>
    <Routes>
    <Route path="/student" element={<StudentPage />} />
    <Route path="/course" element={<CoursePage />} />
    <Route path="/addteacher" element={<AddTeacher />} />
    <Route path="/viewteacher" element={<ViewTacher />} />
    <Route path="/" element={<Home />} />
    </Routes>
    </Router>
    </div>
    );
    };
    export default App;
    
index.js
    import React from "react";
    import ReactDOM from "react-dom";
    import App from "./App";
    ReactDOM.render(<App />, document.getElementById("root"));

how to connect react frontend and koa backend?

this is the code to create react front end and koa backernd In short, the purpose of this SRS document is to provide a software product overview, including software product specifications and goals. This document describes the project’s target groups and user interface, hardware, and software requirements. It defines the perception of a product and its capabilities by customers, teams, and audiences. However, it does support all designers or developers of the Software Delivery Lifecycle (SDLC) process.

Frontend
add to cart
import React from “react”;
import { useState } from “react”;
import axios from ‘axios’;

export default function AddToCart() {
    const [ItemName, setItemName] = useState("");
    const [quntity, setquntity] = useState("");
    const [price, setprice] = useState("");

    let data = {
        ItemName: ItemName,
        quntity: quntity,
        price: price,
    };


    let handleSubmit = async (e) => {
        e.preventDefault();
        try {
            let res = await axios.post("http://localhost:3000/customer/addToCart", data);
            if (res.status === 201) {
                console.log(data);
                alert("Item added successfully");
            } else {
                alert("Some error occured");
            }
        } catch (err) {
            console.log(err);
        }
    };


    return (

        <div>
            <form  onSubmit={handleSubmit}>

                <div >
                    <label >ItemName</label>
                    <input
                        type="text"
                        id="ItemName"
                        value={ItemName}
                        onChange={(e) => setItemName(e.target.value)}
                        required
                    />
                </div>

                <div >
                    <label >Quntity</label>
                    <input
                        type="text"
                        id="quntity"
                        value={quntity}
                        onChange={(e) => setquntity(e.target.value)}
                        required
                    />
                </div>

                <div >
                    <label >price</label>
                    <input
                        type="text"
                        id="price"
                        value={price}
                        onChange={(e) => setprice(e.target.value)}
                        required
                    />
                </div>

                

                <button type="submit">Add to cart</button>
                <button ><a href="/">Back to Dashbord</a></button>
            </form>
        </div>


    );
}


**create profile**
import React from "react";
import { useState } from "react";
import axios from 'axios';

export default function CreateCustomerProfile() {
    const [name, setname] = useState("");
    const [age, setage] = useState("");
    const [mobile, setmobile] = useState("");

    let data = {
        name: name,
        age: age,
        mobile: mobile,
    };


    let handleSubmit = async (e) => {
        e.preventDefault();
        try {
            let res = await axios.post("http://localhost:3000/customer/", data);
            if (res.status === 201) {
                console.log(data);
                alert("profile created successfully");
            } else {
                alert("Some error occured");
            }
        } catch (err) {
            console.log(err);
        }
    };


    return (

        <div>
            <form  onSubmit={handleSubmit}>

                <div >
                    <label >Name</label>
                    <input
                        type="text"
                        id="name"
                        value={name}
                        onChange={(e) => setname(e.target.value)}
                        required
                    />
                </div>

                <div >
                    <label >Age</label>
                    <input
                        type="text"
                        id="age"
                        value={age}
                        onChange={(e) => setage(e.target.value)}
                        required
                    />
                </div>

                <div >
                    <label >Mobile</label>
                    <input
                        type="text"
                        id="mobile"
                        value={mobile}
                        onChange={(e) => setmobile(e.target.value)}
                        required
                    />
                </div>

                

                <button type="submit">Create Profile</button>
                <button ><a href="/">Back to Dashbord</a></button>
            </form>
        </div>


    );
}


**view item**
import React, { useState, useEffect } from 'react';

 export default function viewItems(){
    
    const [Items, setItems] = useState([]);
    
    useEffect(() => {
        fetch("http://localhost:3000/customer/items")
          .then(response => response.json())
          .then((responseData) => {
            setItems(responseData);
          });
        console.log(Items);
      }, []);

       return (
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                {
                    Items.map(item=>{
                    return (<tr key={item.id}>
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                        <td>{item.price}</td>
                    </tr>);
    
                })
            }
            </tbody>
        </table>
    )
    
}
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './index';



ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('app')
);

**Backend**
**db connect**
import {MongoClient} from "mongodb";

const URI = "mongodb://localhost:27017/posts"
const client = new MongoClient(URI);

client.connect();

export default client;

**data adaptor**

import { MongoClient } from "./mongo.Client.js"

const collection = MongoClient.db("posts").collection("postCollections");

const save = async (post) => {
    const inserted = await collection.insertOne(post);
    return inserted.intertedId;
}

export {save};

**api**
import { save } from '../dataAdapter';

const posts = new Map();


const create = async ({
                    title = 'missing title',
                    description = 'missing description',
                    user = 'testUser'
                }) => {
    const post = {title, description, user, posted: new Date()};
    post.id = save(post);
    
    return post;
}

const get = () => {
    return[...posts.values()];
};

const getById = (id) => {
    if(posts.has(id)){
        return posts.get(id);
    }

    throw new Error('Post not found for the Id ${id}');
};

const delPost = (id) => {
    if(posts.has(id)){
        posts.delete(id);
    }
    throw new Error('Not found')
}

export {create, get, getById, delPost};

**routes**
import Router from "@koa/router";
import { create, delPost, get, getById } from "../api/posts.api.js";

 const postRouter = new Router({
    prefix : '/posts'
 });

 postRouter.get('/', (ctx) => {
    ctx.body = get();
 })

 postRouter.get('/:id', (ctx) => {
    const {id} = ctx.params;
    ctx.body = getById(id);
 })

 postRouter.post('/', async (ctx) => {
    const {title, description, user} = ctx.request.body;
    ctx.body = await create({title,description,user});
 })

 postRouter.del('/:id', (ctx) => {
   const {id} = ctx.params.id;
   ctx.body = delPost(id);
 })

 export default postRouter;

**login frontend**
import React, {useState} from 'react';
import axios from "axios";
import {Button, Card, TextField, Typography} from "@mui/material";
import Swal from 'sweetalert2'

const Login = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    let handleSubmit = async (e) => {
        e.preventDefault();

        const StudentResponse= await axios.get("https://floating-meadow-01028.herokuapp.com/api/student/"+email);
        const StaffResponse=await axios.get("https://floating-meadow-01028.herokuapp.com/api/staff/"+email);
        console.log("res:"+ StudentResponse.data);
        console.log("staff res:"+ StaffResponse.data);
        if(StudentResponse.data!==null && email!==""){
            if (password === StudentResponse.data[0].password) {

               await Swal.fire({
                    position: 'top-end',
                    icon: 'success',
                    title: 'Logged In Successfully',
                    showConfirmButton: false,
                    timer: 1500
                })
                localStorage.setItem("loggedInUser", JSON.stringify(StudentResponse.data));
                window.location.href = "/student/dashboard";
            } else {
                alert("Incorrect password");

            }
        }else if(StaffResponse.data!==null && email!==""){
            if (password === StaffResponse.data[0].password) {
              await Swal.fire({
                    position: 'top-end',
                    icon: 'success',
                    title: 'Logged In Successfully',
                    showConfirmButton: false,
                    timer: 1500
                })
                localStorage.setItem("loggedInUser", JSON.stringify(StaffResponse.data));
                console.log(StaffResponse.data[0].role)
                window.location.href = `/${StaffResponse.data[0].role}/dashboard`;
            } else {
                alert("Incorrect password for staff");
            }
        }else{
            alert("please try again!");
        }

    };
    return (
        <div className="container">
            <Typography style={{marginTop:"40px",marginBottom:"40px"}} fontWeight={"bold"} variant={"h3"} className="text-center">RPM Login</Typography>
<Card style={{    paddingLeft: "50px",
    paddingRight: "50px",
    paddingTop:" 50px",
    backgroundColor:"whiteSmoke"
}}>
            <form className="form" >
                <div className="form-group">

                    <TextField
                        label="Email"
                        type="text"
                        fullWidth
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        required
                    />
                </div>

                <div className="form-group">

                    <TextField
                        label="password"
                        type="password"
                        fullWidth
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />
                </div>

                <br></br>
                <Button type="submit" onClick={handleSubmit} variant={"contained"} fullWidth size={"large"} color={"primary"}>
                    Login
                </Button>

                <h5 style={{marginTop:"20px"}}>Not a member? <a href="/SignUpChoose">Create Account</a>< /h5>
            </form>
            <br></br>
</Card>
        </div>
    );
};

export default Login;

**sign up**
import React, {useState} from 'react';
import Grid from '@mui/material/Grid';
import {TextField, Typography, Button, Card} from "@mui/material";
import studentRegistration from "../../assests/studentRegistration.svg";

import "./CSS/index.css"
import SignNav from "./SignNav"
import axios from "axios";
import Swal from "sweetalert2";
// import PasswordField from "material-ui-password-field";


const StudentSignUp = () => {

    const [studentId,setStudentId]=useState("");
    const [userName,setUserName]=useState("");
    const [email,setEmail]=useState("");
    const [contactNumber,setContactNumber]=useState("");
    const [password,setPassword]=useState("");
    const [confPassword,setConfPassword]=useState("");

    const postStudent=()=>{
        axios.post("https://floating-meadow-01028.herokuapp.com/api/student",{
            studentId,
            email,
            userName,
            contactNumber,
            password
        }).then(async res => {
            await Swal.fire({
                position: 'top-end',
                icon: 'success',
                title: 'Student Registered Successfully',
                showConfirmButton: false,
                timer: 2500
            })
            console.log(res)
            window.location.href="/"
        }).catch(err=>{
            console.log(err)
        })
    }



    return (

        <div>

            {/*<SignNav />*/}
            <Card style={{backgroundColor:"whitesmoke",marginTop:"50px", marginLeft:"100px",marginRight:"100px",paddingBottom:"50px"}}>
                <Grid container justifyContent="space-around">

                    <Grid item xs={4}>

                        <img  className="image" src={studentRegistration} alt="60" />
                    </Grid>
                    <Grid item xs={4} style={{marginTop:"20px"}}>

                        <div className="paper">

                            <Typography  component="h1" variant="h4" style={{textAlign:"left",color:"#00007B",fontWeight:"bold"}}>
                                Student Sign up
                            </Typography>
                            <form className="form" noValidate>
                                <TextField
                                    className="textField"
                                    variant="filled"
                                    margin="normal"
                                    required
                                    fullWidth
                                    value={studentId}
                                    onChange={e=>{
                                        setStudentId(e.target.value)
                                    }}
                                    name="studentId"
                                    label="Student ID"
                                />
                                <TextField
                                    className="textField"
                                    variant="filled"
                                    margin="normal"
                                    required
                                    fullWidth
                                    value={userName}
                                    onChange={e=>{
                                        setUserName(e.target.value)
                                    }}
                                    name="userName"
                                    label="User Name"
                                />
                                <TextField
                                    style={{color:"red"}}
                                    className="textField"
                                    variant="filled"
                                    margin="normal"
                                    required
                                    fullWidth
                                    value={email}
                                    onChange={e=>{
                                       setEmail(e.target.value)
                                    }}
                                    label="Email"
                                    name="email"
                                    autoFocus
                                />

                                <TextField
                                    className="textField"
                                    variant="filled"
                                    margin="normal"
                                    required
                                    fullWidth
                                    value={contactNumber}
                                    onChange={e=>{
                                        setContactNumber(e.target.value)
                                    }}
                                    name="contactNumber"
                                    label="Contact Number"
                                />
                                <TextField
                                    className="textField"
                                    variant="filled"
                                    margin="normal"
                                    required
                                    fullWidth
                                    type="password"
                                    value={password}
                                    onChange={e=>{
                                        setPassword(e.target.value)
                                    }}
                                    name="password"
                                    label="Password"
                                />
                                <TextField`enter code here`
                                    className="textField"
                                    variant="filled"
                                    margin="normal"
                                    required
                                    fullWidth
                                    type="password"
                                    value={confPassword}
                                    onChange={e=>{
                                        setConfPassword(e.target.value)
                                    }}
                                    name="confirmPassword"
                                    label="Confirm Password"
                                />


                                <Button
                                    style={{backgroundColor:"#00007B",marginTop:"15px"}}
                                    fullWidth
                                    variant="contained"
                                    size={"large"}
                                    color="primary"
                                    className="submit"
                                    onClick={postStudent}
                                >
                                    Register
                                </Button>

                            </form>
                        </div>

                    </Grid>
                </Grid>
            </Card>
        </div>
    );
};

export default StudentSignUp;

There was an issue with the background returning the LinkedHashMap to the foreground in the wrong order

LinkedHashMap, key is a date String, value is an array of values,

For example, {” 2017-12-01 “: [1, 2, 3],” 2016-12-01 “: [1, 2, 3],” 2015-12-01 “: [1, 2, 3]}, the dates are in reverse order, and the map is returned to the foreground directly in R.

At first, the display order was fine, but then the business came up with new requirements. Instead of always displaying dates in YYYY-MM-DD format, dates were sometimes displayed in YYYY-MM or YYYY format.

Here’s the kicker:

When the date format is YYYY-MM-DD or YYYY-MM, the display sequence is normal and the background is the same. But when the format is YYYY, the order changes from backward to forward when it is returned to the foreground.

Background {” 2017 “: [1, 2, 3],” 2016 “: [1, 2, 3],” 2015 “: [1, 2, 3]} data, to the front desk becomes a {” 2015″ : [1, 2, 3], “2016” : [1, 2, 3], “2017” : [1, 2, 3]}

The keys are all strings, and you can be sure that the order changes as soon as you return them, except when the key is a year.

This problem is very strange, please help to locate the cause, thank you.

Update MySQL field on javascript event

I have this code:

<script>

$(document).on('keypress', '.chat-input', function(){

    var is_typing = 'yes';
    $.ajax({
        url:"typing_status.php",
        method:"POST",
        data:{is_typing:is_typing},
        success:function()
        {

        }
    })
});

$(document).on('focus', '.chat_input', function(){
    var is_typing = 'no';
    $.ajax({
        url:"typing_status.php",
        method:"POST",
        data:{is_typing:is_typing},
        success:function()
        {
            
        }
    })
});

The first event on keypress updates the field to “yes” but the second one on focus doesen’t update the field to “no”.

Any idea what I’m doing wrong?