Import mapping doesn’t seems to be working with Node.JS

Import mapping is a new feature in Javascript that allows usage of absolute paths rather than relative paths, making restructuring projects easier.

According to the docs, I have to put a imports object to the package.json.

Here is a example file that has this imports:

{
  "dependencies": {
    "dotenv": "^16.0.3",
    "express": "^4.18.2"
  },
  "imports": {
    "#stuff": {
      "app": "./app.js"
    }
  },  
  "type": "module"
}

and a example minimal snippet of code that tries to use app.js by import mapping

import { app } from "#stuff/app"

If I run the server with the code and the log:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
node:internal/errors:478
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_PACKAGE_IMPORT_NOT_DEFINED]: Package import specifier "#stuff/app" is not defined in package /home//Desktop//package.json imported from /home//Desktop//server.js
    at new NodeError (node:internal/errors:387:5)
    at throwImportNotDefined (node:internal/modules/esm/resolve:354:9)
    at packageImportsResolve (node:internal/modules/esm/resolve:737:3)
    at moduleResolve (node:internal/modules/esm/resolve:895:21)
    at defaultResolve (node:internal/modules/esm/resolve:1115:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:837:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36) {
  code: 'ERR_PACKAGE_IMPORT_NOT_DEFINED'
}
[nodemon] app crashed - waiting for file changes before starting...

Side note: app.js actually does exists but I don’t include here due it contains my own private code.

JS How to use one single input value in more functions

This site must do the following things:

  1. I type “MERAVIGLIA” and click on the first button, and the first door must open.
  2. I do the same things with the rest of the WORDS and all the doors must open one after another.

But it doesn’t work: the first door opens but the following ones don’t.
I don’t know how to fix it!

Suggestions?

<html>
    <head>
        <title>
            Porta
        </title>
        <style>
            .backDoor
            {
              background-color: rgb(74, 52, 25);
            position:center;
            top:0px;
            left:0px;
            width:250px;
            height:540px;
            margin: 0 auto;
            margin-top:100px;
            }

            .door
            {
            background-color: rgb(74, 52, 25);
            background-image: url(porta.png);
            position:center;
            top:0px;
            left:0px;
            width:250px;
            height:540px;
            margin: 0 auto;
            margin-top:100px;
            
            transform-origin: left;
            /*Speed of the Door animation*/
            transition: all 0.5s ease-in-out;
            }

            .doorOpen
            {
            /*prespectiv creates the door open effect*/
            transform: perspective(1200px) translateZ(0px) translateX(0px) translateY(0px) rotateY(-110deg);
            }

            body {
                background-color: black;
                background-image: url(parete.jpg);
            }

            .door2 {
              background-color: rgb(74, 52, 25);
              background-image: url(porta.png);
              position:center;
            top:0px;
            left:0px;
            width:250px;
            height:540px;
            transform-origin: left;
            margin: 0 auto;
            margin-top:100px;
            /*Speed of the Door animation*/
            transition: all 0.5s ease-in-out;
            }

            .door3 {
              background-color: rgb(74, 52, 25);
              background-image: url(porta.png);
              position:center;
            top:0px;
            left:0px;
            width:250px;
            height:540px;
            transform-origin: left;
            margin: 0 auto;
            margin-top:100px;
            /*Speed of the Door animation*/
            transition: all 0.5s ease-in-out;
            }

            .door4 {
              background-color: rgb(74, 52, 25);
              background-image: url(porta.png);
              position:center;
            top:0px;
            left:0px;
            width:250px;
            height:540px;
            transform-origin: left;
            margin: 0 auto;
            margin-top:100px;
            /*Speed of the Door animation*/
            transition: all 0.5s ease-in-out;
            }

            .door5 {
              background-color: rgb(74, 52, 25);
              background-image: url(porta.png);
              position:center;
            top:0px;
            left:0px;
            width:250px;
            height:540px;
            transform-origin: left;
            margin: 0 auto;
            margin-top:100px;
            /*Speed of the Door animation*/
            transition: all 0.5s ease-in-out;
            }
         </style>
    </head>
    <body>
      <div class="backDoor">
      <div class="door5">
        <div class="door4">
          <div class="door3">
              <div class="door2">
                <div class="door">  
            </div>
          </div>
        </div>
      </div>
    </div>
          </div>
          <div>
            <input type="text" id="parola">
          </input>
          <button id="button1" onclick="toggleDoor()">
            Apri prima porta
          </button>
          <button id="button2" onclick="toggleDoor2()">
            Apri seconda porta
          </button>
          <button id="button3" onclick="toggleDoor3()">
            Apri terza porta
          </button>
          <button id="button4" onclick="toggleDoor4()">
            Apri quarta porta
          </button>
          <button id="button5" onclick="toggleDoor5()">
            Apri quinta porta
          </button>
          </div>
          <script>
              var parola=document.getElementById("parola").value;
                  var element = document.querySelector(".door");
           //     element.addEventListener("click", toggleDoor)
                  function toggleDoor() {
                    if(parola=="MERAVIGLIA") {

                  element.classList.toggle("doorOpen");
                  }
                }

                var element2 = document.querySelector(".door2");
           //     element.addEventListener("click", toggleDoor)
                function toggleDoor2() {
                  if(parola=="FIDUCIA") {

                element2.classList.toggle("doorOpen");}
                }

                var element3 = document.querySelector(".door3");
           //     element.addEventListener("click", toggleDoor)
                function toggleDoor3() {
                  if(parola=="ACCOGLIENZA") {
                element3.classList.toggle("doorOpen"); }
                }

                var element4 = document.querySelector(".door4");
           //     element.addEventListener("click", toggleDoor)
                function toggleDoor4() {
                  if(parola=="BUONENOTIZIE") {

                element4.classList.toggle("doorOpen");}
                }

                var element5 = document.querySelector(".door5");
           //     element.addEventListener("click", toggleDoor)
                function toggleDoor5() {
                  if(parola=="CAMMINAREINSIEME") {

                element5.classList.toggle("doorOpen");
                }}
         </script>
    </body>
    <footer>
        
    </footer>
</html>

how to push nest object data to array

i’m learning right now play with chartjs and i want ask about how to push nested object data to array, but just only specific data as example:

 "Pelajar Pejuang - Jl Peta": {
        "00:00:00": {
          "date": "2022-12-18",
          "start_time": "00:00:00",
          "end_time": "01:00:00",
          "total_hourly": 150
        },
        "01:00:00": {
          "date": "2022-12-18",
          "start_time": "01:00:00",
          "end_time": "02:00:00",
          "total_hourly": 133
        },
 "02:00:00":null,
}

that above data i want to push in array variable become like this :

const barChartLoc1 = reactive({
      chartData: {
        labels: [
          "01:00",
          "02:00",
          "03:00",
        ],
        datasets: [
          {
            data: [
              155, 133, 0,
            ],
            backgroundColor: ["#6225E3", "#E32525", "#E7A543"],
          
          },
        ],
      },
      chartOptions: {
        maintainAspectRatio: false,
        responsive: true,
 
      },
    });

that result of data above, every null data become 0.

thank u for helping me guys 🙂

Is it possible to fill in multiple inputs in parallel with Puppeteer?

I want to type into 2 inputs at the same time but in fact both texts go to the second input.

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  await page.goto("https://example.com");

  await Promise.all([
    page.type("#user", "user"),
    page.type("#password", "password"),
  ]);

  await browser.close();
})();

The second input looks like upsaesrsword

Use If statement within $$eval to test variable

I’m trying to extract text from a website using Puppeteer. So far I wrote the following code which is working but the “if” within $$eval doesn’t.
What I’m trying to do is to check if order_total is empty and in that case extract it from a different position but it doesn’t work.

let orders = await page.$$eval('.order-item', elements => elements.map(item => {
    let order_date = item.innerText.split('n')[1];
    let order_ID = (item.innerText.split('n')[2]).replace('Order ID: ', '');
    let store_name = item.innerText.split('n')[5];
    let order_total = item.innerText.split('n')[9];
    if (item.innerText.split('n')[9] == '') {
        order_total = item.innerText.split('n')[7]
    }
    return {
        order_date,
        order_ID,
        store_name,
        order_total
    }
}));
console.log(JSON.stringify(orders))

My problem is that sometimes “order_total” with element 9 is empty and I would like to extract it from element 7 which in that case would have what I’m looking for.

Could you please help me to understand what I’m doing wrong?

Thanks a lot in advance for your help!

Function returning undefined

I have a function that calls an API and returns some data:

async function getDataAxios(){
        await axios.get("http://localhost:8080/cards/1").then(response => {
                console.log("RESP: ", response.data[0])
                return response
            })
            .catch(err => {
            console.log("Error: ", err)
            return err
        })
}

When I log response.data[0] inside getDataAxios() the expected data is present.
But when I try and return the data to my calling function and log the return data it logs undefined:

getDataAxios().then(r => console.log(r))

I have also tried the following:

 const resp = getDataAxios().then(resp => console.log("Data 2: ", resp)).catch(
    err => {
        console.log("An error has occurred: ", err)
        return err;
    }
  )
    console.log(resp)

Full code:

function App() {
    getDataAxios().then(r => console.log(r))
}

async function getDataAxios(){
        await axios.get("http://localhost:8080/cards/1").then(response => {
                console.log("RESP: ", response.data[0])
                return response
            })
            .catch(err => {
            console.log("Error: ", err)
            return err
        })
}

export default App;

How can I make a user-selected them apply on all pages?

I’m working on a website project, and I need a way for a user to select the theme to be light or dark. Ideally I would like the light and dark themes to be stored in different css files, and actuated by a button. I also need the styles to be applied across all pages, and to change to the selected theme no matter what page the user is on.

Also is there any way to make this possible without using databases? I’m aiming to make this site a self-contained offline package, working off of localhost. Is this at all possible? Thanks in advance

CommerceJS not returning product with variants

I am calling the CommerceJS API, I get all the details for the products, except one, the variants.I am making a store for shoes, and I am not able to get the sizes available that I set on CommerceJS. The variants and groups are all saved, but I do not get them in the API call.
I modified some data due to privacy reasons, but here is what I get back:

`

{
  "id": "id",
  "created": 1669104344,
  "updated": 1671313359,
  "active": true,
  "permalink": "permalink",
  "name": "Air Force 1 Low",
  "description": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>",
  "price": {
    "raw": 99.99,
    "formatted": "99.99",
    "formatted_with_symbol": "$99.99",
    "formatted_with_code": "99.99 USD"
  },
  "inventory": { "managed": true, "available": 100 },
  "sku": "AF1L",
  "sort_order": 0,
  "seo": { "title": null, "description": null },
  "thank_you_url": null,
  "meta": null,
  "conditionals": {
    "is_active": true,
    "is_tax_exempt": false,
    "is_pay_what_you_want": false,
    "is_inventory_managed": true,
    "is_sold_out": false,
    "has_digital_delivery": false,
    "has_physical_delivery": false,
    "has_images": true,
    "collects_fullname": true,
    "collects_shipping_address": true,
    "collects_billing_address": true,
    "collects_extra_fields": false
  },
  "is": {
    "active": true,
    "tax_exempt": false,
    "pay_what_you_want": false,
    "inventory_managed": true,
    "sold_out": false
  },
  "has": {
    "digital_delivery": false,
    "physical_delivery": false,
    "images": true
  },
  "collects": {
    "fullname": true,
    "shipping_address": true,
    "billing_address": true,
    "extra_fields": false
  },
  "checkout_url": {
    "checkout": "checkout",
    "display": "display"
  },
  "categories": [
    {
      "id": "id",
      "slug": "mens-collection",
      "name": "Mens Collection"
    }
  ],
  "image": {
    "id": "id",
    "url": "url",
    "description": null,
    "is_image": true,
    "filename": "af1l.png",
    "file_size": 10470,
    "file_extension": "png",
    "image_dimensions": { "width": 592, "height": 592 },
    "meta": [],
    "created_at": 1669104326,
    "updated_at": 1669104328
  }
}

`

I tried modifying and saving the variants again, but still not working.

Elrond Smart Contract call via JavaScript SDK returns a user error

I am trying to call a function from a Elrond Smart Contract to create a NFT, I am using their JavaScript SDK.

This is the error I get:

TransactionCompletionStrategy.isCompleted(), found event: signalError

Transaction return code: user error

This is my JavaScript code:

const {
  Transaction,
  BytesValue,
  ContractCallPayloadBuilder,
  ContractFunction,
  BigUIntValue,
  Account,
  Address,
  TransactionWatcher,
  ResultsParser,
} = require('@elrondnetwork/erdjs')
const { BigNumber } = require('bignumber.js')
const fs = require('fs')
const {
  UserSecretKey,
  UserSigner,
  parseUserKey,
} = require('@elrondnetwork/erdjs-walletcore')
const {
  ProxyNetworkProvider,
} = require('@elrondnetwork/erdjs-network-providers')

const contractAddress = new Address(
  'erd1qqqqqqqqqqqqqpgqlsd27rdekm3px5aydfahf9lcau0wrss3rfyqtvvxke',
)
const specialOpertationsGasLimit = 3_000_000
let attributes, hash

const setup = async () => {
  const pemKeyFileName = './mypemfile.pem'
  const walletPemKey = fs.readFileSync(pemKeyFileName, 'utf8')
  const pemKey = UserSecretKey.fromPem(walletPemKey)
  const signer = new UserSigner(pemKey)

  const provider = new ProxyNetworkProvider('https://devnet-gateway.elrond.com')

  const userKey = parseUserKey(walletPemKey)
  const account = new Account(userKey.generatePublicKey().toAddress())
  let accountOnNetwork = await provider.getAccount(
    userKey.generatePublicKey().toAddress(),
  )
  account.update(accountOnNetwork)

  return {
    signer,
    account,
    provider,
  }
}

const commonTxOperations = async (tx, account, signer, provider) => {
  tx.setNonce(account.getNonceThenIncrement())
  signer.sign(tx)
  await provider.sendTransaction(tx)
  const watcher = new TransactionWatcher(provider)
  const transactionOnNetwork = await watcher.awaitCompleted(tx)

  const txHash = transactionOnNetwork.hash
  const txStatus = transactionOnNetwork.status

  let { returnCode } = new ResultsParser().parseUntypedOutcome(
    transactionOnNetwork,
  )

  console.log(`nTransaction return code: ${returnCode}`)
  console.log(`nTransaction status: ${txStatus}`)
  console.log(
    `Transaction link: https://devnet-explorer.elrond.com/transactions/${txHash}n`,
  )
}

const createNft = async () => {
  try {
    const { name, royalties, uri, sellingPrice } = {
      name: 'testifulify',
      royalties: 5,
      uri:
        'https://dweb.link/ipfs/bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
      sellingPrice: 50000000000000000n, //(0.05 EGLD)
    }

    const { signer, account, provider } = await setup()

    const args = [
      BytesValue.fromUTF8(name),
      new BigUIntValue(new BigNumber(Number(royalties) * 100 || 0)),
      BytesValue.fromUTF8(uri || ''),
      new BigUIntValue(new BigNumber(Number(sellingPrice) || 0)),
    ]

    const data = new ContractCallPayloadBuilder()
      .setFunction(new ContractFunction('createNft'))
      .setArgs(args)
      .build()

    const tx = new Transaction({
      data,
      gasLimit:
        specialOpertationsGasLimit +
        data.length() * 1500 +
        (attributes?.length || 0 + hash?.length || 0) * 50000,
      receiver: contractAddress,
      sender: signer.getAddress(),
      value: 0,
      chainID: 'D',
    })

    await commonTxOperations(tx, account, signer, provider)
  } catch (e) {
    console.log(e?.message)
  }
}

createNft()

I am using their NFT Minter example from this repository https://github.com/ElrondNetwork/elrond-wasm-rs/blob/master/contracts/examples/nft-minter/src/lib.rs

The Smart Contract is deployed to the Devnet https://devnet-explorer.elrond.com/accounts/erd1qqqqqqqqqqqqqpgqlsd27rdekm3px5aydfahf9lcau0wrss3rfyqtvvxke

Really appreciate, because I am stuck at the moment, tried different variations to call the contract but getting always the same error.

How to link to a react website from a non react website?

So I have a sort of portfolio website that i made using plain html/css/javascript. And another project that I made using react which fires up with “npm run start”.
Now I have a link in my portfolio website’s index.html that links to that project , something like-

<a  target="_blank"  href="./work/WebWork/public/index.html">
              <span>WebWork </span>
</a>

here the WebWork project is the react project which I’m mentioning in my portweb to showcase what I did, but when I click on it , it loads a blank.
How can I fix that?

port already in use

node:events:491
throw er; // Unhandled ‘error’ event
^

Error: listen EADDRINUSE: address already in use :::3001
at Server.setupListenHandle [as _listen2] (node:net:1463:16)
at listenInCluster (node:net:1511:12)
at Server.listen (node:net:1599:7)
at Function.listen (C:UsersAKHIL-1servernode_modulesexpresslibapplication.js:635:24)
at file:///C:/Users/AKHIL-1/server/index.js:62:9
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted ‘error’ event on Server instance at:
at emitErrorNT (node:net:1490:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: ‘EADDRINUSE’,
errno: -4091,
syscall: ‘listen’,
address: ‘::’,
port: 3001
}

{
    "version": "0.2.0",
    "configurations": [
        {
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "name": "nodemon",
            "program": "${workspaceFolder}/app.js",
            "request": "launch",
            "restart": true,
            "runtimeExecutable": "nodemon",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "type": "node"
        }
    ]
}

Pass control prop to child component in react hook form

I’m trying to pass the control prop to my custom component that comes from react-hook-form but it tells that the control is undefined

I did the same thing written in document. I used FormProvider like this:

<FormProvider {...methods}>
        <form
          style={{
            height: "auto",
            width: "90%",
            padding: "2em",
            paddingTop: "0",
            textAlign: "center",
            backgroundColor: "white",
            borderRadius: "10px",
          }}
          onSubmit={methods.handleSubmit((data) => console.log(data))}
        >
          <IconButton
            color="error"
            onClick={() => setRecordControl({ stat: "" })}
          >
            <Cancel fontSize="large" />
          </IconButton>
          <h3 style={{ marginBottom: "10px", textAlign: "center" }}>
            saving records
          </h3>
          {filtered.ListColumnInfo.map(
            (detail) =>
              detail.VisibleColumn && (
                <div key={uuidV4()}>
                  <CustomTextBoxComponent
                    filtered={detail}
                  />
                </div>
              )
          )}

          <Button
            variant="contained"
            fullWidth
            color="success"
            sx={{ mt: "1em" }}
            type="submit"
          >
            save
          </Button>
        </form>
      </FormProvider>

and I tried to retrieve the control inside of my CustomTextBoxComponent like this:

const CustomTextBoxComponent = ({ filtered }) => {
  const { control } = useFormContext();
  return (
    <Controller
      name="input"
      render={({ field }) => (
        <TextField
          fullWidth
          placeholder={
            filtered.ElsRecord.PersianName !== ""
              ? filtered.ElsRecord.PersianName
              : filtered.ElsRecord.Name
          }
    
          sx={{ marginBlock: "1em" }}
          {...control}
          {...field}
        />
      )}
      defaultValue=""
    />
  );
};

it didn’t work. always says the method is null

Reduce data json HTML markup?

enter image description here

I am trying to figure out how to hide the last 12 numbers on price in the button, as it is way to long.

I am using a JSON api, and insertAjacentHTML markup.

This is the code.

`

<script>
    fetch('https://free-api.vestige.fi/asset/467518794/price')
      .then(res => {
        console.log(res);
        return res.json();
      })
      .then(data => {
       console.log(data.price);
         const markup = `<a>${data.price}</a>`;
         document.querySelector('button').insertAdjacentHTML('beforeEnd', markup);
      })
      .catch(error => console.log(error));
</script>

`

I tried a couple of different methods, but I am just not too great with json and javascript together.

On page refresh I get this error: TypeError: Cannot read properties of undefined (reading ‘name’)

My app is working fine and I can refresh other pages. But when I refresh the page where an event is being edited (EditEvent Component) it gives me this error message: Uncaught TypeError: Cannot read properties of undefined (reading ‘name’). And I’ve noticed that all my state variables are “undefined” after the refresh, even at the top level(App.js). Can someone please help?

App.js

import React from "react";
import { Routes,  Route } from 'react-router-dom';
import { useState, useEffect } from "react";
import Home from "./components/Home";
import SignUp from "./components/SignUp";
import Login from "./components/Login";
import EditEvent from "./components/EditEvent";
import NewEvent from "./components/NewEvent";



function App() {

  const [currentUser, setCurrentUser] = useState("");
  const [events, setEvents] = useState([])
  const [clients, setClients] = useState([])
  
  useEffect(() => {
    fetch('/auth')
    .then(r => {
      if(r.ok){
        r.json().then(user => {
          setCurrentUser(user)
          setClients(user.clients)
        }
          )
      }
    })
  },[])

  useEffect(() => {
    fetch('/events')
    .then(r => {
      if(r.ok){
        r.json().then(events => setEvents(events)
          )
      }
    })
  },[])



  function handleLogin(user) {
    setCurrentUser(user)
  }

  function handleSetUser(user) {
    setCurrentUser(user)
  }

  function handleEditEvent(editedEvent) {
    const unchangedEvents = events.filter(event => event.id !== editedEvent.id)
    setEvents([...unchangedEvents,editedEvent])

  }

  function handleDeleteEvent(deletedEvent){
    const updatedEvents = events.filter((event) => event.id !== deletedEvent.id)
    setEvents([...updatedEvents])
  }

  function handleNewEvent(newEvent) {
    setEvents([...events,newEvent])
  }

  console.log(events)
  return (
    <div className="App">
      <Routes>
        <Route path="/home" element ={<Home currentUser={currentUser} setCurrentUser={setCurrentUser} events={events} clients={clients} onEventDelete={handleDeleteEvent} addEvent={handleNewEvent}/>} />
        <Route path="/" element={<Login onLogin={handleLogin}/>} />
        <Route path="/signup" element={<SignUp setUser={handleSetUser}/>} />
        <Route path="/events/:id" element={<EditEvent events={events} clients={clients} onEditEvent={handleEditEvent} />} />
        <Route path="/newevent" element={<NewEvent events={events} clients={clients} addEvent={handleNewEvent}/>} />
      </Routes>

    </div>
  );
}

export default App;

Home.js

import React from 'react';
import NavBar from './NavBar';
import Events from './Events';
import Vendors from './Vendors';
import { useState } from "react"
import NewEvent from './NewEvent';

function Home({ currentUser, setCurrentUser, events, clients, onEventDelete, addEvent }) {

    const [active, setActive] = useState('Events')

    return (


        <div>
            <NavBar currentUser={currentUser} setCurrentUser={setCurrentUser} setActive = {setActive}/>
            {active === "Events" && <Events events={events} clients={clients} onEventDelete={onEventDelete} />}
            {active === "Vendors" && <Vendors />}
            {active === "NewEvent" && <NewEvent clients={clients} addEvent={addEvent} currentUser={currentUser} setActive={'Events'}/>}
        </div>


    );
}

export default Home;



Events.js

import React from "react";
import EventCard from "./EventCard";
import "../Container.css";

function Events ( { events, onEventDelete } ) {

  const renderEvents = events.sort( (a,b) => a.id > b.id ? 1 : -1).map((event) => ( <EventCard key={event.id} event={event} onEventDelete={onEventDelete}/> ))

    return (
        <section className="twitter">
        <h1 className="header">Upcoming Events</h1>
        <div className="container">
          {renderEvents}
        </div>
      </section>
    )

}

export default Events;

EventCard.js

import React from 'react';
import { useNavigate } from 'react-router-dom'
import "../Container.css";

function EventCard( { event, onEventDelete }) {

    const navigate = useNavigate();

    function handleEventDelete() {
        fetch(`/events/${event.id}`, {
            method: 'DELETE'
        })
        .then(()=> {
            onEventDelete(event)
        });
    }

    function getTime(eventTime) {

        const time = eventTime.split('T')[1];
        const hour = time.split(':')[0];
        const minutes = time.split(':')[1];
        let timeValue = '';
        if (hour > 0 && hour <= 12) {
            timeValue= "" + hour
          } else if (hour > 12) {
            timeValue= "" + (hour - 12);
          } else if (hour === 0) {
            timeValue= "12"
          }

        const standardTime = timeValue + ':' + minutes;
        const dayNight =  timeValue = (hour >= 12) ? " P.M." : " A.M.";

        return standardTime + dayNight;

    }

    function handleEdit(e) {
        e.preventDefault()
        navigate(`/events/${event.id}`)
    }

    return ( <div className='card' >
         <h1 className='title'>{event.name}</h1>
             <p>Client: {event.client.name}</p>
             <p>Date: {event.start_date}</p>
             <p>Time: {getTime(event.start_time)}</p>
             <p>Location: {event.location}</p>
             <p>Description: {event.description}</p>
             <br></br>
             <ul>
                Vendors:
                {event.vendors.map((vendor) => 
                <li key={vendor.id}>{vendor.name}</li>)}
             </ul>

                 <button id='edit-button' onClick={handleEdit} >Edit</button >
             <button id='delete-button' onClick={handleEventDelete}>Delete Event</button>
       </div>) 
     

 
    
}

export default EventCard;

EditEvent.js

import React from 'react'
import { useState } from "react";
import { Link, useNavigate, useParams} from "react-router-dom";
import "../index.css"


function EditEvent ( { events, onEditEvent, clients } ) {
    

    const params = useParams();
    const event = events.find((event) => event.id == params.id)
    const navigate = useNavigate();

    


   
    const [name, setName] = useState(event.name);
    const [description, setDescription] = useState(event.description);
    const [location, setLocation] = useState(event.location);
    const [budget, setBudget] = useState(event.budget);
    const [currentCost, setCurrentCost] = useState(event.current_cost);
    const [startDate, setStartDate] = useState(event.start_date);
    const [startTime, setStartTime] = useState(getTime(event.start_time));
    const [endDate, setEndDate] = useState(event.end_date);
    const [endTime, setEndTime] = useState(event.end_time);
    const [selectedClient, setSelectedClient] = useState(event.client.name)

    function getTime(eventTime) {

        const time = eventTime.split('T')[1];
        const hour = time.split(':')[0];
        const minutes = time.split(':')[1];
        let timeValue = '';
        if (hour > 0 && hour <= 12) {
            timeValue= "" + hour
          } else if (hour > 12) {
            timeValue= "" + (hour - 12);
          } else if (hour == 0) {
            timeValue= "12"
          }

        const standardTime = timeValue + ':' + minutes;
        const dayNight =  timeValue = (hour >= 12) ? " P.M." : " A.M.";

        return standardTime + dayNight;

    }

    function handleClientChange(e) {
        setSelectedClient(e.target.value)
   }

    function handleSubmitChanges(e) {
        e.preventDefault()

        const client = clients.find((client) => client.name == selectedClient)

        const editedEvent = {
            name: name,
            description: description,
            start_date: startDate,
            start_time: startTime,
            end_date: endDate,
            end_time: endTime,
            locaiton: location,
            budget: budget,
            current_cost: currentCost,
            id: event.id,
            client_id: client.id,
        }


        fetch(`/events/${editedEvent.id}`, {
            method: 'PATCH',
            headers: {
                'Content-Type' : 'application/json'
            },
            body: JSON.stringify(editedEvent)
        })
        .then(r => r.json())
        .then(editedEvent => {
            onEditEvent(editedEvent)
            navigate("/home")
        })
        

    }


    console.log(selectedClient)

  return event ? (

        <div className='edit-background'>
         <form className="edit-form" onSubmit={handleSubmitChanges}>
             <div className="edit-title">Edit Event</div>
             <div className="input-container ic0">
                <input  id="name" className="input" type="text"  defaultValue={name}  onChange={(e) => setName(e.target.value)}/>
                <label className="edit-cut edit-cut-short">Name</label>
            </div>
            <div className="input-container ic0">
                <input id="desc" className="input" type="text" defaultValue={description} onChange={(e) => setDescription(e.target.value)}/>
                <label className="edit-cut edit-cut-short">Description</label>
            </div>
            <div className="input-container ic0">
                <input id="start-date" className="input" type="text" defaultValue={startDate} onChange={(e) => setStartDate(e.target.value)}/>
                <label className="edit-cut edit-cut-short">Start Date</label>
            </div>
            <div className="input-container ic0">
                 <input id="start-time" className="input" type="text" defaultValue={startTime}  onChange={(e) => setStartTime(e.target.value)}/>
                <label className="edit-cut edit-cut-short">Start Time</label>
            </div>
            <div className="input-container ic0">
                <input id="end-date" className="input" type="text" defaultValue={endDate} onChange={(e) => setEndDate(e.target.value)}/>
                <label className="edit-cut edit-cut-short">End Date</label>
            </div>
            <div className="input-container ic0">
                 <input id="end-time" className="input" type="text" defaultValue={endTime} onChange={(e) => setEndTime(e.target.value)}/>
                <label className="edit-cut edit-cut-short">End Time</label>
            </div>
            <div className="input-container ic0">
                <input id="location" className="input" type="text" defaultValue={location} onChange={(e) => setLocation(e.target.value)}/>
                <label className="edit-cut edit-cut-short">Location</label>
            </div>
            <div className="input-container ic0">
                <input id="budget" className="input" type="text" defaultValue={budget} onChange={(e) => setBudget(e.target.value)}/>
                <label className="edit-cut edit-cut-short">Budget</label>
            </div>
            <div className="input-container ic0">
                <input id="current-cost" className="input" type="integer"  defaultValue={currentCost} onChange={(e) => setCurrentCost(e.target.value)}/>
                <label className="edit-cut edit-cut-short">Current Cost</label>
            </div>
            <select value={selectedClient} onChange={handleClientChange}>
                {clients.map((client) => <option key={client.id}>{client.name}</option>)}
            </select>
            <button type="submit" className="submit">Edit</button>
            <Link to={"/home"}>
                <button id='submit'>Cancel</button >
            </ Link>
         </form>
        </div>
        
    ) : null
};

export default EditEvent;

NavBar.js


import React from "react";
import "../NavBar.css";
import { useNavigate } from 'react-router-dom';

function NavBar( {currentUser, setCurrentUser, setActive } ) {

    const navigate = useNavigate()

    function handleLogOut() {
        navigate('/')
        fetch('/logout',{method: "DELETE"}).then((r) => {
            if(r.ok){
                setCurrentUser(null)
            }
        })
    };

return (
<main className="main">
  <aside className="sidebar">
    <p className="greeting">Hello {currentUser.first_name}</p>
    <nav className="nav">
        <button className="nav-button" onClick={() => setActive("NewEvent")}>New Event</button>
        <button className="nav-button" onClick={() => setActive("Events")}>Events</button>
        <button className="nav-button" onClick={() => setActive("Vendors")}>Vendors</button>
        <button className="nav-button" onClick={handleLogOut}>Logout</button>
    </nav>

  </aside>
</main>
)

}

export default NavBar;