cannot setState in onInputChange fuction in React-select?

I am using React-select Autocomplete search like the below screenshot. but I cannot collect input field value. there is no getting error or something. but I cannot type more than 1 letter after setState.

but only log this input value work log show porperly.

enter image description here

<AutoCompleteSearch
  isLoading={isLoading}
  options={filterOptions || []}
  className='w-full mr-3'
  onChange={(selectOption: any) => {
      handleFilterOptionChange(selectOption)
  }}
  onInputChange={(inputValue: any) => {
      console.log(event) //work properly
      setSelectedKeyWord(inputValue) //after added this not work cannot type and not set state
  }}
/>

in Storybook use component

import React, { FC, useState } from 'react'
import Select, { components } from 'react-select'
import CN from 'classnames'

export interface AutoCompleteSearchProps {
  [x: string]: any
  defaultValue?: { id: any; value: any; label: string | number }
  isClearable?: boolean | true
  isDisabled?: boolean
  isLoading?: boolean | false
  isMultiple?: boolean | false
  isSearchable?: boolean | true
  onChange?: any
  onInputChange?: any
  options: { id: any; value: any; label: string | number }[]
  placeHolder?: string | 'Search'
  value?: { id: any; value: any; label: string | number }
}

export const AutoCompleteSearch: FC<AutoCompleteSearchProps> = ({
  className,
  defaultValue,
  isClearable,
  isLoading,
  isMultiple,
  isSearchable,
  onInputChange,
  onChange,
  options,
  placeHolder,
  value,
  ...restProps
}: AutoCompleteSearchProps) => {
  const AutoCompleteSearchClasses = CN(`auto-complete-search`, className, {})

  const [keyword, setKeyWord] = useState('')

  function ValueContainer({ children, ...props }: any) {
    return (
      components.ValueContainer && (
        <components.ValueContainer {...props}>
          {!!children && (
            <i
              className='ri-search-line ri-lg text-N-500'
              aria-hidden='true'
              style={{ position: 'absolute', left: 14 }}
            />
          )}
          {children}
        </components.ValueContainer>
      )
    )
  }

  const styles = {
    valueContainer: (base: any) => ({
      ...base,
      paddingLeft: 40,
    }),
    control: (base: any) => ({
      ...base,
      'border': '1px solid #CCD6E1',
      'borderRadius': '3px',
      'boxShadow': '0px 1px 2px rgba(0, 45, 71, 0.05)',
      '&:hover': {
        border: '1px solid #CCD6E1',
      },
      '&:focus': {
        border: '1px solid #3570AB',
        boxShadow:
          '0px 0px 4px rgba(0, 89, 141, 0.24), inset 0px 0px 4px rgba(0, 58, 89, 0.5)',
      },
    }),
    menuPortal: (base: any) => ({ ...base, zIndex: 9999 }),
    option: (base: any, { isFocused }: any) => ({
      ...base,
      backgroundColor: isFocused ? '#EEF3F8' : '#fff',
      color: '#2E3849',
    }),
  }

  return (
    <div className={AutoCompleteSearchClasses} {...restProps}>
      <Select
        components={{
          ValueContainer,
          DropdownIndicator: () => null,
          IndicatorSeparator: () => null,
        }}
        defaultValue={defaultValue}
        isClearable={isClearable}
        isSearchable={isSearchable}
        isLoading={isLoading}
        isMulti={isMultiple}
        options={options}
        onChange={onChange}
        onInputChange={onInputChange}
        menuPosition='fixed'
        placeholder={
          <span className='select-placeholder-text text-N-500'>
            {placeHolder}
          </span>
        }
        styles={styles}
        value={value}
      />
    </div>
  )
}

AutoCompleteSearch.defaultProps = {
  defaultValue: undefined,
  isClearable: true,
  isSearchable: true,
  isLoading: false,
  isMultiple: false,
  onChange: () => {},
  onInputChange: () => {},
  options: [],
  placeHolder: 'Search',
  value: undefined,
}

export default AutoCompleteSearch

exactly I want to catch React input type value and set it useState.
anyone can help me or can you guys know another method do this?

Getting Undefined When Trying to Request Const Data From Reactjs File in my NodeJS Express API

I have a file named check-rates that holds some useStates() that the users will input in order for me to execute and return for them an estimated value for their shipment by using DHL API.

In my nodejs express server, I am trying to access these useStates() with req.body but when I console log the constants I always get them as undefined. I need these values that the user enters so that the API becomes dynamic for each customer/user that uses my website and not fixed values (as I have them now.)

What am I doing wrong?

here is my code:

Check-Rates.js:

const [fromCountires,setFromCountries] = useState("");
const [fromCountriesCode,setFromCountriesCode] = useState("");
const [fromCountriesCapital,setFromCountriesCapital] = useState("");
const [fromPostalCode,setFromPostalCode] = useState("");
const [toCountries,setToCountries] = useState("");
const [toCountriesCode,setToCountriesCode] = useState("");
const [toCountriesCapital,setToCountriesCapital] = useState("");
const [weight,setWeight] = useState("");
const [data,setData] = useState(null);

 const getRateEstimate = () => {
    
        axios.get('http://localhost:3001/api/dhl').then(response => {
            console.log(response)
            setData(response.data);
        }).catch(e => {
            console.log(e)
        });
    }

return (
 //example of how i am setting my needed useStates...
<Form.Group controlId="exampleForm.ControlInput1">
   <Form.Label className={'fw-bold'}>Weight</Form.Label>
   <Form.Control type="text" placeholder="" onChange={(e)=> {
     setWeight(e.target.value)}}/>
 </Form.Group>

  <button className={'btn-orange fw-bold py-2 px-3 px-4 rounded getRateBtn'}
  type={'submit'} onClick={getRateEstimate}> Check
  </button>
)

NodeJS Server

index.js:

app.get('/api/dhl', (req, res) => {

    const accountNum = req.body.accountNum
    const fromCountriesCode = req.body.fromCountriesCode
    const fromCountriesCapital = req.body.fromCountriesCapital
    const toCountriesCode = req.body.toCountriesCode
    const toCountriesCapital = req.body.toCountriesCapital
    const weight = req.body.weight
    const plannedShippingDate = req.body.date
    const len = "5"
    const width = "5"
    const height = "5"
    const isCustomsDeclarable = 'false'
    const unitOfMeasurement = 'metric'

    console.log(weight)//logs undefined
    console.log(fromCountriesCapital)//logs undefined

    var options = { method: 'POST',
    url: 'https://express.api.dhl.com/mydhlapi/test/rates',
    headers: 
     { 'postman-token': '',
       'cache-control': 'no-cache',
       authorization: 'Basic AUTH',
       'content-type': 'application/json' },
    body: 
     { customerDetails: 
        { shipperDetails: 
           { postalCode: '19010',
             cityName: 'Dubai',//need this
             countryCode: 'BH',//need this
             addressLine1: '0' },//end Shipper DETAILS
          receiverDetails: 
           { postalCode: '76321',
             cityName: 'Riyadh',//need this
             addressLine1: '0',
             countryCode: 'SA' }//end Reciever DETAILS
             },
       accounts: [ { typeCode: 'shipper', number: 'myAccountNumbeer' } ],
       plannedShippingDateAndTime: '2021-08-25T13:00:00GMT+00:00',//need thiss
       unitOfMeasurement: 'metric',
       isCustomsDeclarable: true,
       monetaryAmount: [ { typeCode: 'declaredValue', value: 10, currency: 'BHD' } ],
       requestAllValueAddedServices: false,
       returnStandardProductsOnly: false,
       nextBusinessDay: false,
       packages: [ { weight: 25, dimensions: { length: 5, width: 5, height: 5 } } ] },
    json: true };
  
  request(options, function (error, response, body) {
    if (error) throw new Error(error);
    res.send(body)
    console.log(body);
  });
});

Getting PostgresSQL 42703 error (invalid column error)

I am working on a React project with PostgreSQL database, this is the first time I am using it, and I am getting 42703 error on querying a particular column.

Below is the code I have written to query

const getList = (userId) => {

    return new Promise(function (resolve, reject) {
        pool.query(`SELECT items FROM public."user" where id=${userId}`, (error, results) => {
            if (error) {
                reject(error)
            }
            resolve(results);
        })
    })
}

I have defined this getList function and then I am making an api call to call this function by passing the userId like this

app.get(`/expenses`, verifySession(), async (req, res) => {
    const userId = req.session.userId;
    database.getList(userId)
        .then(response => {
            res.status(200).send(response);
        })
        .catch(error => {
            res.status(500).send(error);
        })
})

I even tried passing the userId directly as shown below , still it gives me the same error , which probably means I am querying in a wrong way

app.get(`/expenses`, verifySession(), async (req, res) => {
    //const userId = req.session.userId;
    database.getList('17a6dea6-a63e-4da7-9910-df7eddb672e6')
        .then(response => {
            res.status(200).send(response);
        })
        .catch(error => {
            res.status(500).send(error);
        })
})

Only when I directly write the string in the query it works properly like this

const getList = (userId) => {

    return new Promise(function (resolve, reject) {
        pool.query(`SELECT items FROM public."user" where id='17a6dea6-a63e-4da7-9910-df7eddb672e6'`, (error, results) => {
            if (error) {
                reject(error)
            }
            resolve(results);
        })
    })
}

Can someone please help we with what is exactly going wrong and if my syntax is correct or not ?

DIfferentiating between multiple event listeners

Can someone explain where my thinking goes wrong here ?
I have a class that adds a mousedown event listener to a specified canvas.
I make two instances of the class attached to two different canvases.
I expect to get responses from both instances but all responses say they’re from the second instance.

class Mycanvas{
  constructor (canvas,name){
    self = this;
    this.name=name;
    canvas.addEventListener('mousedown', mousedown);
  }
  function mousedown(){console.log(self.name)}
}
let mycanvas1 = Mycanvas(canvas1,'1');
let mycanvas2 = Mycanvas(canvas2,'2');

BUT, this code works fine :

class Mycanvas{
  constructor (canvas,name){
    this.name=name;
    canvas.addEventListener('mousedown', ()=>console.log(this.name));
  }
}
let mycanvas1 = Mycanvas(canvas1,'1');
let mycanvas2 = Mycanvas(canvas2,'2');

How can I find Date from the day in JavaScript?

Let me clear the question suppose today is Thursday and I select Monday from the select dropdown then It will give the date of the upcoming Monday and If I select Saturday then It will give me the date of two days after means upcoming Saturday not a next week Saturday and so on.

how to check if a string includes all array elements

how to check if a string includes all array elements, regardless of element’s position inside the string

for example:

var arr = ['lorem', 'ipsum', 'dolor'];
var str = 'lorem blue dolor sky ipsum';

I need something like this:

if(str.includesAll(arr)){console.log('string includes all elements');}
else{console.log('string does not include all elements');}

[Error: Query.Mutation defined in resolvers, but not in schema]

const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');

const port = process.env.PORT || 4000;
const notes = [
    { id: '1', content: 'This is a note', author: 'Adam Scott' },
    { id: '2', content: 'This is another note', author: 'Harlow Everly' },
    { id: '3', content: 'Oh hey look, another note!', author: 'Riley Harrison' }
   ];

const typeDefs = gql `
    type Note {
        id: ID
        content: String
        author: String
    }

    type Query {
        hello: String
        notes: [Note]
        note(id: ID!): Note
    }

    type Mutation {
        newNote(content: String!): Note
    }
`;
const resolvers = {
    Query:{
        hello: () => 'Hello World',
        notes: () => notes,
        note: (parent, args) => {
            return notes.find(note => note.id == args.id);
        },
    Mutation: {
        newNote: (parent, args) => {
            let noteValue = {
                id : String(notes.length + 1),
                content : args.content,
                author: 'Adam Scott',
            };
            notes.push(noteValue);
            return noteValue;
        }
    }
    },
}

Some people had naming issues but seems that I’m using the same in resolver as well as in schema.
Please bare with me, this is my second day in GraphQL and Express. I removed intentionally imports and assignment of express object, middleware since it does not let me post.

Using .map() method to render array items into their own separate divs, but comma is still displaying?

I’ve searched and searched but I’ve only found solutions to .join() the items into a single string..this is my first question so I’ll try my best to explain thoroughly.

const createCard = () => {
    const pokemonTypes = ['grass', 'fire', 'water'];
      return (
        `<div>
          ${pokemonTypes.map(type => `<div>${type}</div>`)}
        </div>`
      )
}

document.body.insertAdjacentHTML("beforeend", createCard());

For some context, I am using an API but I simplified the code so it’s quick and easy to read.

I am trying to display each string into its own div so that I can style each div separately…like color coded buttons: green for grass, blue for water, red for fire etc.

When I run the code the strings successfully display in their own div, however the comma remains. I’d like them to just display next to each without the comma separating them.

Thank you!

Access Alpine to create magic properties from standalone js file

I try to implement Alpine JS within a existing page.

For that, I’m using the CDN version of Alpine, which I’m loading within my :

<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

Now I’m trying to access Alpine from a custom.js file, which is loaded automatically within the footer of my page:

Alpine.magic('post', function () {
    return function (url, data = {}) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            redirect: 'follow',
            body: JSON.stringify(data)
        });
    }
});

Within my content I tried this:

<div x-data>
    <h1>Alpine Test</h1>
    <button type="button" @click="$post('/api/users', { name: 'John Doe' })">Add user</button>
</div>

By clicking the button, this error occurs:

Uncaught ReferenceError: $post is not defined

I’ve also tried it with window.Alpine, without success.

How can I add magic properties and stuff like that without using modules?

How can I setting Dynamic Serialport parameters? NodeJS

I’m using Node.js serialport for electron in raspberrypi4
https://serialport.io/docs/
but I can’t setting Dynamic parameters for serialport

Here is my code

var portname, baudrate, databits, stopbits, Parity, RTSCTS;
var portOpen = false;

const port = new serialport('COM4', {
    baudRate: baudrate,
    dataBits: databits,
    stopBits: stopbits,
    parity: Parity,
    rtscts: RTSCTS,
    autoOpen: false,
})

This code is error in electron “TypeError: “baudRate” must be a number: undefined at new SerialPort”

Baudrate is using port.update() for dynamic parameter,
but other things is not available.
Please help me