Typescript: Generic function should not return union of all types

I managed to type the object currentProps so TS knows which properties it haves AND each property has its individual type (not an union of all possible types).

So far so good.

Then I have this generic function overrideForIndex which gets one of the possible properties, and should return its value. But it can’t be assigned, because its return-type is a union, and not the specific type.

Now I could just cast it as any and call it a day, but I am curious if there is a way to handle this properly without casting to any.

Here is the “simplified” example:
(open in TS playground)

export type MyProps = {
  id?: number;
  title?: string;
}

const props: Record<keyof MyProps, any> = {
  id: 123,
  title: 'foo'
}

export const propNames = Object.keys(props) as Array<keyof MyProps>;

const data: Record<number, MyProps> = { 0: { id: 123, title: 'foo' }};

const buildLatestProps = (): { [P in keyof Required<MyProps>]: MyProps[P] } => {
  const getLatest = <T extends keyof MyProps>(propName: T) => data[0][propName];
  return Object.fromEntries(propNames.map(n => [n, getLatest(n)])) as any;
};

const currentProps = buildLatestProps();

const overrideForIndex = <T extends keyof MyProps>(propName: T, index: number): MyProps[T] =>
  data[index][propName];

propNames.forEach(n => (currentProps[n] = overrideForIndex(n, 0) /* as any */)); // ERR: Type 'string | number | undefined' is not assignable to type 'undefined'.

Display images from google drive link

hello I am making a project in React js in which I want to get the help that how can I achieve this task
In a dashboard, there is an option in which users paste their public google drive folder link and in this folder, there will be images
once the user paste their google drive link and click on the upload button all images from the folder will start display on dashboard

Increase and decrease the number using addEventListener keydown in React

I wrote a program that adds or subtracts a unit to count by pressing the up and down keys on the keyboard.
The problem is that the program does not work properly. When you press the key, look at the console, which runs several times, while each time you press the key, it only has to run once.
This is a problem that crashes after pressing the up or down buttons a few times, please help

import React, { useState } from "react";

export default function Example() {
  const [count, setCount] = useState(0);

  document.addEventListener("keydown", function (e) {
    switch (e.keyCode) {
      case 38:
        setCount(count + 1);
        console.log(count);
        break;
      case 40:
        setCount(count - 1);
        console.log(count);
        break;
    }
  });
  return (
    <div>
      <p>You clicked {count} times</p>
    </div>
  );
}

JavaScript setattribute after searchParams in URL

I do some options in this code.

first, get Attribute by getAttribute() this called ‘src’.

second, use 'searchParams.set()' to change resize in this URL.

third, setAttribute() to accepte last change of size.

this is my code:

<!DOCTYPE html>
<html>
    <head>
        <style>
          #twoposition {
              position: absolute;
              width: 100%;
              height: 100%;
              left: 0px;
              top: 50px;
          }
        </style>
        
        <title></title>
    </head>
    <body>
        <select onchange="check()" id="selectbox" name="">
            <option hidden value="empty"></option>
            <option value="firstSize">1</option>
            <option value="secondSize">2</option>
        </select>
        <div id="two">
            <div id="de6854">
                <div style="width: 100%;height: 100%">
                    <iframe id="4526d" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
                    </iframe>
                    <iframe id="3ad34" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
                    </iframe>
                </div>
            </div>
        </div>

    </body>
        <script>
            function check() {
                var val = document.getElementById("selectbox").value
                var pic =  document.querySelectorAll("#two iframe")
                var aa = pic.getAttribute('src')
                
                var url = new URL(aa);
                var url0 = url.searchParams.set('resize', '500,300');
                var url2 = url.searchParams.set('resize', '400,200');
                
                if(val === "firstSize") {
                    pic.setAttribute('src',url0)
                } 
                else if(val === "secondSize") {
                    pic.setAttribute('src',url2)
                }
            }
        </script>
</html>

I try this code but not working.

I want if I select the check 1 has value firstSize change the attribute to url0.

and if I select the check 2 has value secondSize change the attribute to url2.

HTML get checkbox element

I’m making a checkbox where every user presses the checkbox, then the contents of the checkbox will appear in the list section :
as shown here

the problem is the checkbox that works is only the first checkbox in the list and every time the user presses the checkbox, the content that shown in the list is only the last data in the database.
here is my code :

@foreach($users as $user)
                                    <ol class="list-group" >
                                            <div class="card">
                                            <li class="list-group-item group-containers">
                                                <div class="row">
                                                <input onclick="checkBox(this)" class="form-check-input" type="checkbox" id="approver">
                                                    <div class="col-1 c-avatar mr-3">
                                                        <img class="c-avatar-img" src="{{ url('/assets/img/avatars/3.png') }}">
                                                    </div>
                                                    <div class="col-8">
                                                    <div class="">{{ $user->name }}</div>
                                                    <label for="" class="text-secondary">{{ $user->email }}</label>
                                                    </div>
                                                </div>
                                                </input>
                                            </li>
                                        </div>
                                    </ol>
                                    @endforeach

Here is the code that shows the selected checkbox content :

<ol id="list" class="list-group" style="display:none">
                            <div class="card">
                                <li class="list-group-item">
                                    <div class="row">
                                        <div class="col-1 c-avatar mr-3">
                                            <img class="c-avatar-img" src="{{ url('/assets/img/avatars/3.png') }}">
                                        </div>
                                        <div class="col-8">
                                        <div class="">{{ $user->name }}</div>
                                    </div>
                                </li>
                                </div>
                            </ol>

and here is the javascript code :

<script>
    
function checkBox(){
    // console.log(e)
    var cb = document.getElementById("approver");
    var text = document.getElementById("list");
    if(cb.checked==true){
        text.style.display="block";
    } else {
        text.style.display="none";
    }
}

</script>

any solutions?

ReferenceError: ResizeObserver is not defined:Gatsby with nivo

I use @nivo/pie with "gatsby": "^3.13.0".
But I got an error when I gatsby build.
WebpackError: ReferenceError: ResizeObserver is not defined
I have no idea to solve it. I would be appreciate if you could give me some advice.

And here is the React code using nivo’s pie chart.

PieChart.tsx

import React from 'react'
import { ResponsivePie } from '@nivo/pie'

const PieChart: React.FC = ({ data }) => {
  return (
    <>
      <div>
        <ResponsivePie
            data={data}
            margin={{ top: 30, right: 80, bottom: 70, left: 80 }}
            borderColor={{
                from: 'color',
                modifiers: [
                    [
                        'darker',
                        0.2,
                    ],
                ],
            }}
            arcLabelsTextColor={{
                from: 'color',
                modifiers: [
                    [
                        'darker',
                        2,
                    ],
                ],
            }}
            fill={[
                {
                    match: {
                        id: 'ruby',
                    },
                    id: 'dots',
                },
            ]}
            legends={[
              {
                  anchor: 'bottom-right',
                  direction: 'column',
                  justify: false,
                  translateX: 0,
                  translateY: -1,
              },
          ]}
          />
      </div>
    </>
  )
}

export default PieChart

Thank you.

Regarding amazon-connect-streams ccp softphone

how can we stop initialize below code many times after succesffully logged in via help of javascript?

      connect.core.initCCP(containerDiv, {
      ccpUrl: instanceURL,            // REQUIRED
      loginPopup: true,               // optional, defaults to `true`
      region: "eu-central-1",         // REQUIRED for `CHAT`, optional otherwise
      softphone: {                    // optional, defaults below apply if not provided
        allowFramedSoftphone: true,   // optional, defaults to false
      }

need quick help on this.!

RavenDB can’t perform search with AND operator on nodejs

How can I perform a search with ‘AND’ operator via RavenDB?

Based on the docs it’s written that I need to add the operator enum (“AND” “OR”) as the third parameter of the search function.
https://ravendb.net/docs/article-page/4.0/nodejs/client-api/session/querying/how-to-use-search

From some reason the AND operator does not work and it gives me OR results by default.

Example:

Users collection:

users/1-A: {
    firstName: 'Joe',
    lastName: 'Allen'
}

users/2-A: {
    firstName: 'Joe',
    lastName: 'Biden'
}

The call to raven:

session.query({ collection: 'Users' })
.search('firstName', 'Joe', 'AND') // search with AND operator
.search('lastName', 'Biden')
.all()

The call above returns back both documents.
What should be the appropriate syntax for that?

Thanks

Reactjs not calling onChange callback in child

I have written a re-usable input component for url if a url dont start with http then it will be added http in the beginning.

Here you go for the componet

import React, {useContext, useCallback} from 'react';


const InputURL = ({ name, onChange, ...rest}) => {


    const sanitizeURLonChange = React.useCallback((value, actionMeta) => {
        if (value.target.value) {
            if (!value.target.value.startsWith('http')) {
                value.target.value = 'http://' + value.target.value
            }
        }

    }, [onChange])


    return (
        <>
           <input
               name={name}
               {...rest}
               onChange={sanitizeURLonChange}
            />
        </>
    );
}

export default InputURL;

But when i try to use it in my some component, the onChange doesnt work

I try this way

<inputURL onChange={(e)} => console.log(e.target.value)  />

unfortunately the inputURL onChange not working anymore, can you please help me in this case?

JSON Conversion from json object to JSON array of object [closed]

{
“0”: {
“name”: “ABC”,
“first_name”: “abc”,
“mobile”: “1111111111”,
“dailing_code”: “91”,
“email”: “[email protected]
},
“1”: {
“name”: “XYZ”,
“first_name”: “xyz”,
“mobile”: “2222222222”,
“dailing_code”: “91”,
“email”: “[email protected]
},
“2”: {
“name”: “PQRS”,
“first_name”: “pqrs”,
“mobile”: “8888888888”,
“dailing_code”: “91”,
“email”: “[email protected]
}
}

Convert from above giver JSON to below JSON

[
{
“name”: “ABC”,
“first_name”: “abc”,
“mobile”: “1111111111”,
“dailing_code”: “91”,
“email”: “[email protected]
},
{
“name”: “XYZ”,
“first_name”: “xyz”,
“mobile”: “2222222222”,
“dailing_code”: “91”,
“email”: “[email protected]
},
{
“name”: “PQRS”,
“first_name”: “pqrs”,
“mobile”: “8888888888”,
“dailing_code”: “91”,
“email”: “[email protected]
}
]

Take user input of 5 Cards and find highest card pair from five cards

  1. . If your collection contains at least one pair, return an array of two elements: true and the card number of the highest pair.
    Eg: highestCardPair([“A”, “A”, “Q”, “Q”, “6” ]) –> [true, “A”]
    highestCardPair([“J”, “6”, “3”, “10”, “8”]) –> false
    highestPair([“3”, “5”, “5”, “5”, “5”]) ➞ [true, “5”] – three or more of the same card still count as containing a pair

javascript breaks menu behaviour

I have nav bar that shrinks depending on the screen width and the button appears that toggles the dropdown menu. When I triggered the dropdown menu using checkbox (pure CSS), it worked perfectly. But after I started to use js instead of checkbox, it started to break the nav bar behaviour. When I shrink the window then press the button to toggle the dropdown menu and then expand window back, the nav bar doesn’t revert back to it’s “default” state. How to make the nav bar revert back to its state when the screen width increases? Is there any ability to apply style ONLY to media query css style but not to the main style? Here’s my code:

const menuButton = document.querySelector('.menuButton')
const menuDisplay = document.querySelector('nav ul')

menuButton.addEventListener('click', () => {
  if (menuDisplay.style.display == 'none') {
    menuDisplay.style.display = 'initial'
    setTimeout(() => {
      menuDisplay.style.height = '100vh'
    }, 0)
  } else {
    setTimeout(() => {
      menuDisplay.style.display = 'none'
    }, 300)
    menuDisplay.style.height = '0'
  }
})
header {
  background-color: rgba(24, 24, 24, 0.95);
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 10;
}

.menuButton {
  display: none;
  position: fixed;
  right: 0;
  color: white;
  font-size: 1.5em;
  line-height: 65px;
  margin: 10 30px;
  cursor: pointer;
}

.logo {
  color: white;
  font-size: 30px;
  font-weight: bold;
  font-family: 'Fredoka One', sans-serif;
  line-height: 65px;
}

nav {
  padding: 10px 5%;
  display: flex;
  max-width: 900px;
  margin: auto;
  justify-content: space-between;
  align-items: center;
  -moz-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

nav ul {
  display: flex;
  list-style: none;
  font-weight: bold;
}

nav ul li a {
  display: block;
  text-align: center;
  padding: 14px 16px;
  margin: 5px;
}

.orderButton {
  border-radius: 5px;
  background-color: #e8e8e8;
  color: black;
  border: 2px solid #e8e8e8;
  text-align: center;
  padding: 14px 16px;
  margin: 5px;
  cursor: pointer;
  transition: all.3s ease;
  -webkit-transition: all.3s ease;
  -o-transition: all.3s ease;
  -moz-transition: all.3s ease;
}

.orderButton:hover {
  background-color: rgba(0, 0, 0, 0);
  color: white;
}

nav ul li .active {
  color: #999999;
}

@media (max-width: 600px) {
  nav ul {
    width: 100%;
    text-align: center;
    transition: margin-top 0.3s ease-in-out, height 0.3s ease-in-out;
    -webkit-transition: margin-top 0.3s ease-in-out, height 0.3s ease-in-out;
    -moz-transition: margin-top 0.3s ease-in-out, height 0.3s ease-in-out;
    flex-direction: column;
    overflow: hidden;
    height: 0;
    display: none;
  }
  nav ul li {
    margin: 20px;
  }
  nav {
    flex-direction: column;
  }
  .logo {
    text-align: center;
  }
  .menuButton {
    display: block;
  }
}
<header>
  <div class="menuButton">&#9776;</div>
  <nav>
    <a href="index.html">
      <h1 class="logo">Cite</h1>
    </a>
    <ul>
      <li>
        <div class="orderButton">Заказать</div>
      </li>
      <div class="orderForm">
        <div class="form-wrap">
          <h2>Данные для связи</h2>
          <form method="post" action="order.php">

            <p>Имя</p>
            <input type="text" name="name" value="" placeholder="Имя" />

            <p>Телефон</p>
            <input type="tel" name="phone" value="" placeholder="Телефон" />

            <p>Почта</p>
            <input type="email" name="email" value="" placeholder="E-mail" />

            <p>Комментарий</p>
            <textarea name="other" placeholder="Комментарий к заявке"></textarea>
          </form>
        </div>
      </div>
      <li><a href="about.html">О нас</a></li>
      <li><a href="contact.html">Контакты</a></li>
    </ul>
  </nav>

  <script src="js/script.js" type="text/javascript"></script>

</header>

Fetch function for ExactOnline with multiple request error on zapier and n8n

I’ve been working on a script that creates and updates stuff with the ExactOnline API.

when I run the script locally everything works fine but when I try to use it on a platform such as Zapier or n8n it doesn’t work as intended.

on Zapier it only runs just before it does a fetch request

this my code that I use in zapier:

var token = 'token';
var divisionid = 'divisionid';

var AMRelatieData = {
  "Name": "company name",
  "City": "city name",
  "Website": "website.com"
};


var AMContactData = {
  "FirstName": "firstname",
  "LastName": "lastname", 
  "City": "name city"
};
var testrlid;

async function actionHandeler(actionValue) {

  var action = actionValue;
  if (action == "cp_maken_&_relatie_maken") { 

    var maakRelatieWaarde = await maakRelatie(AMRelatieData);

      var POSTrelatieID = maakRelatieWaarde;

      AMContactData.Account = POSTrelatieID;

      var maakContactwaarde = await maakContact(AMContactData);
        var POSTcontactID = maakContactwaarde;

        testcpid = POSTcontactID;
        testrlid = POSTrelatieID;

  return ('maakContactwaarde succes');

  }

  //functions
  async function updateRelatie(updateData, relatieId) {

    var UpdateRelatiePUT = await PUTreq(1, updateData, relatieId);

    console.log(UpdateRelatiePUT);

    return ("updateRelatie succes");
  }

  async function maakRelatie(createData) {
    var relatieId;

    console.log('maakRelatie: ');

    var maakRelatiePOST = await POSTreq(1, createData); 

    console.log('maakRelatieFunc:' + JSON.stringify(maakRelatiePOST));

    return await maakRelatiePOST.d.ID;
  }

  async function maakContact(createData) {
    var contactId;


    var maaktcontactPOST = await POSTreq(2, createData);

    console.log('maaktcontactFunc:' + JSON.stringify(maaktcontactPOST));


    var jsonData = {
      MainContact: maaktcontactPOST.d.ID
    };

    var relatieIdUpdate = createData.Account;
    await updateRelatie(jsonData, relatieIdUpdate);
  }

  async function POSTreq(type, DATA) {
    console.log('postreq');

    var POSTendpoint = 'https://start.exactonline.nl/api/v1/'+ divisionid +'/crm/';
    if (type == 1) {

      POSTendpoint += 'Accounts';
    }
    if (type == 2) {

      POSTendpoint += 'Contacts';
    }

    var outputPOST;
    console.log(DATA);
    await fetch(POSTendpoint, {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(DATA)
    }).then(response => {
      return response.json();
    }).then(jsonResponse => {
      var responseOut = jsonResponse;
      outputPOST = responseOut;
    }).catch(error => {
      console.log(error);
    });
    return outputPOST;
  }

  async function PUTreq(type, DATA, id) {
    var PUTendpoint = 'https://start.exactonline.nl/api/v1/'+ divisionid +'/crm/';

    console.log('put data');
    console.log(id);
    console.log('data' + DATA);
    console.log(type);

    if (type == 1) {
      PUTendpoint += "Accounts(guid'" + id + "')";
    }
    if (type == 2) {
      PUTendpoint += "Contacts(guid'" + id + "')";
    }

    console.log(PUTendpoint);
    console.log(PUTendpoint);
    await fetch(PUTendpoint, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token
      },
      body: JSON.stringify(DATA)
    });
  }
}


async function actionHandlerFunc(){
  console.log("begin");
  await actionHandeler("cp_maken_&_relatie_maken");

  return ("done did sum stuff");
};



output = [actionHandlerFunc()]