React State Update Issue: Updating One Field Erases Other Fields

I’m working on a React component where I need to update the state of an object that holds values for different days. However, when I update one field, the other fields get erased completely, leaving the object with only the field I changed.

Here’s the relevant part of my code:

const [dayValues, setDayValues] = useState({});

const handleInputChange = (day, field, value) => {
  setDayValues(prevValues => ({
    ...prevValues, // for preserving all other days
    [day]: {
      ...prevValues[day], // for preserving the other fields i dont change
      [field]: value
    }
  }));
};

I have a state object dayValues that looks something like this:

{
  "2023-10-01": { field1: 5, field2: 3, field3: 8 },
  "2023-10-02": { field1: 2, field2: 4, field3: 2 }
}

When I call for example handleInputChange("2023-10-01", "field2", 4) via a Numberinput with increment and decrement buttons like this:

<NumberInput onChange={(newField2Value) => handleInputChange(day, "field2", newField2Value)}/> 

I expect the state to update to:

{
  "2023-10-01": { field1: 5, field2: 4, field3: 8 },
  "2023-10-02": { field1: 2, field2: 4, field3: 2 }
}

However, what actually happens is:

{
  "2023-10-01": { field2: 4 },
  "2023-10-02": { field1: 2, field2: 4, field3: 2 }
}

Why does my current implementation erase the other fields, and how can I fix it to preserve the existing fields while updating only the specific field?

Any help would be greatly appreciated!

MSE: SouceBuffer doesn’t seem to append data

I am trying to append an ArrayBuffer of a chunk of a mp4 file to a SourceBuffer. After struggling with this for a few days it does append without giving an error. So I guess the format is good.

But when I console.log the SourceBuffer.buffered attribute it stays empty. I’m using sequence as mode.

const buffer = Buffer.concat(tempBuffer);
tempBuffer = [];
const blob = new Blob([buffer], { type: mimeCodec });
const arrayBuffer = await blob.arrayBuffer();
            
console.log(sourceBuffer);
try {
   sourceBuffer.appendBuffer(arrayBuffer);
} catch (error) {
   console.log('Error appending to buffer', error);
}

This is how I’m appending data to the SourceBuffer. Every time there is a chunk coming from the api I store it in a temporary buffer. Then when the tempbuffer is appended to the SourceBuffer. I empty the temp buffer.

This is working because I don’t have any errors. I can appendBuffer a complete movie without errors. But when I console.log the sourceBuffer it stays empty:

buffered doesn't have any values

When I play the video nothing happens just a black screen. So I guess the appending of the buffer isn’t working as it should be. I have no clue what to do now. Documentation is very limited and I can’t find any support groups on discord or other channels.

Why is my SourceBuffer still empty while the appendBuffer method doesn’t throw an error.

Thanks in advance!

API works for simple company names, but fails for longer name in google sheet. How to fix? [closed]

Subject: Help Needed: API Doesn’t Fetch Domain for Complex Company Names

Hi everyone,

I recently watched a video (https://www.youtube.com/watch?v=M7N_tBcwEDI) where the API works well for company names that consist of one or two words, like “Google” or “IBM.” However, for more complex names, such as those including “Pvt Ltd” or longer company names, it fails to find the domain, even though Google search can easily find it.

Could someone kindly suggest the necessary changes to the API to handle more complex company names effectively?

Thanks in advance for your help!

IN Google sheet:
Cell A2 has Company name

In the App Script:

const base_url_clearbit = "https://autocomplete.clearbit.com/v1/companies/";

function clearbit_getDomain(name) {
  var suggest_url = base_url_clearbit + 'suggest?query=' + name;
  var suggest_response = UrlFetchApp.fetch(suggest_url);
  var suggest_response_text = JSON.parse(suggest_response.getContentText());
  var domain = suggest_response_text[0]['domain'];
  return domain;
}

in the google sheet cell C2:

=clearbit_getDomain(A2)

Kindly amend the coding of API to get the required result

Javascript React app “fetch” returning ‘undefined’ on reload from browser, but returning data when reloading from API

I have a component that pulls a json object from github

async function getQueryJson(URL)
{
 await fetch(URL) // This gets the git commits
.then( (res) => res.json()) //Converts it to a JSON
.then(
(result) => {
  setCommits(result) // This puts the JSON containing the commits made to gitlocale into state
  console.log("Outputting value of GQJ")
  console.log(commits)
},
(error) => {console.log("Error in fetch: "+error)}
)
}`

which is called within the UseEffect portion of my React code to populate a State with an array of JSON objects.

useEffect(() =>
     {
    var userObject = {}
    getQueryJson(githubCommits)

My issue is that when I first refresh the page, the the “commits” returns as “undefined” – if I change my code in my IDE which reloads the page, the “commits” returns an array of JSON and the code executes properly.

To complicate matters further, if I output (res.json()) to the console, I receive the JSON object in all circumstances regardless or not of if my state is set to undefined, which makes me nervous about the execution.

Am I correctly using the async fetch function?
I don’t think I need to perform this twice. It has the json object,but on a first visit it does not process the json.

I have removed the async/await portion, which did not affect functionality.
I have moved the results to another state, which receives the undefined/json object the same, so it’s not being incidentally initialized multiple times
I have attempted to pull the JSON independently from the fetch, which didn’t work.

Testing ShadCN Select with Jest and React testing Library

I have a ShadCN Select component that is abstracted into a CustomSelect component for reusability. I am trying to test the click functionality of the options and assert the text content on the Select button but I’m faced with this error

Unable to find an element with the text: /latest products/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    Ignored nodes: comments, script, style
    <body>
      <div>
        <div
          class="min-w-40"
        >
          <button
            aria-autocomplete="none"
            aria-controls="radix-:r7:"
            aria-expanded="false"
            class="flex h-10 items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 w-full"
            data-state="closed"
            dir="ltr"
            role="combobox"
            type="button"
          >
            <span
              style="pointer-events: none;"
            >
              All Products
            </span>
            <svg
              aria-hidden="true"
              class="lucide lucide-chevron-down h-4 w-4 opacity-50"
              fill="none"
              height="24"
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              viewBox="0 0 24 24"
              width="24"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="m6 9 6 6 6-6"
              />
            </svg>
          </button>
        </div>
      </div>
    </body>

I have been trying to fix this issue in the last hour but I haven’t been lucky enough yet. Below is what my test file looks like:

import { screen, render } from "@testing-library/react";
import ProductSortMenu from "../product-sort-menu";
import userEvent from "@testing-library/user-event";
import { useRouter } from "next/navigation";

jest.mock("next/navigation", () => {
  const replace = jest.fn();
  return {
    useSearchParams: () => new URLSearchParams(""),
    usePathname: jest.fn().mockReturnValue("/products"),
    useRouter: jest.fn().mockReturnValue({ replace }),
  };
});

describe("ProductSortMenu", () => {
  it("render the select menu component", () => {
    render(<ProductSortMenu />);
    const selectElement = screen.getByRole("combobox");
    expect(selectElement).toBeInTheDocument();
  });

  it("updates the url when the selected option changes", async () => {
    const user = userEvent.setup();
    const { replace } = useRouter();

    render(<ProductSortMenu />);

    const selectButtonElement = screen.getByRole("combobox");

    expect(selectButtonElement).toHaveTextContent(/all products/i);
    expect(replace).toHaveBeenCalledTimes(0);

    await user.click(selectButtonElement);

    const latestProductsOption = await screen.findByText(
      /latest products/i,
      {},
      { timeout: 3000 }
    );
    await user.click(latestProductsOption);

    expect(selectButtonElement).toHaveTextContent(/latest products/i);
    expect(replace).toHaveBeenCalledTimes(1);
    expect(replace).toHaveBeenCalledWith("/products?sort_by=created_at_desc");
  });
});

Please note: The error is thrown when I tried to access the latestProductOption variable. Also, this is what my actual component looks like:

"use client";

import React from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

import CustomSelect from "../shared/custom-select";

type SelectValues =
  | "all products"
  | "oldest products"
  | "latest products"
  | "lowest price"
  | "highest price";

export default function ProductSortMenu() {
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const { replace } = useRouter();

  const onValueChangeHandler = (value: SelectValues): void => {
    const params = new URLSearchParams(searchParams);

    if (value === "lowest price") {
      params.set("sort_by", "price_asc");
    } else if (value === "highest price") {
      params.set("sort_by", "price_desc");
    } else if (value === "oldest products") {
      params.set("sort_by", "created_at_asc");
    } else if (value === "latest products") {
      params.set("sort_by", "created_at_desc");
    } else {
      params.delete("sort_by");
    }

    replace(`${pathname}?${params.toString()}`);
  };

  return (
    <div className="min-w-40">
      <CustomSelect
        options={[
          "All Products",
          "Latest Products",
          "Oldest Products",
          "Lowest Price",
          "Highest Price",
        ]}
        defaultValue="all products"
        placeholder="Sort By"
        label="Sort products"
        onValueChange={onValueChangeHandler}
      />
    </div>
  );
}

Any pointer to why I am experiencing this error would be greatly appreciated.

Toggle visibillity of a list in Svelte

I am trying to do the most basic thing in Svelte but I keep failing. I want the button element to trigger the visibillity of the ul-element with classname “this-one”. I am stuck in the “vanilla js”-approach and can not wrap my head around how to achieve this the svelte-way. Any pointers?

        <ul>
            <li>
                <ul>
                    {#each item.children as child (child.id)}
                        <li>
                            <div>
                                <a href={child.route.path} on:click={() => dispatch('click')}>
                                    <span>{child.name}</span>
                                </a>
                                {#if child.children?.length > 0}
                                    <button>
                                        <i class="chevron-down"></i>
                                    </button>
                                {/if}
                            </div>
                            {#if child.children?.length > 0}
                                <ul class="this-one">
                                    {#each child.children as grandChild}
                                        <li>
                                            <a href={grandChild.route.path} on:click={() => dispatch('click')}>
                                                {grandChild.name}
                                            </a>
                                        </li>
                                    {/each}
                                </ul>
                            {/if}
                        </li>
                    {/each}
                </ul>
            </li>
        </ul>

How to Disable Auto-Scrolling to the Bottom in Microsoft Bot Framework Web Chat?

I’m using Microsoft Bot Framework Web Chat CDN for my chatbot. Whenever a new bot message appears, the chat automatically scrolls to the bottom, which hides earlier messages. I want to disable this auto-scrolling so that users can view new messages starting from the top of the chat window, rather than being taken to the bottom each time

What I tried:

I attempted to customize the Web Chat behavior using the scrollToEnd middleware and JavaScript to control scrolling, but these approaches either did not prevent auto-scrolling or affected the overall chat experience in ways I did not intend.

What I was expecting:

I expected to disable auto-scrolling so that new messages would appear at the top of the chat window, allowing users to see the content from the beginning of the conversation without being automatically scrolled to the bottom.

problem with cypress in fs-extra does not allow me to run tests

the present problem is that when I try to place a wait and a timeout to one of my tests it shows me this error

I hope that the test will run normally because with this error no test will work.

I suspect that this error is specifically related to the fs-extra library.

No commands were issued in this test.
TypeError
The following error originated from your test code, not from Cypress.

> Cannot read properties of undefined (reading 'native')

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.
node_modules/get-uri/node_modules/fs-extra/lib/fs/index.js:133:1
  131 |
  132 | // fs.realpath.native sometimes not available if fs is monkey-patched
> 133 | if (typeof fs.realpath.native === 'function') {
      | ^
  134 |   exports.realpath.native = u(fs.realpath.native)
  135 | } else {

136 | process.emitWarning(

How to change request header of websocket connection from chrome extension service worker

On invoking the below function, the console message “Token rule update with new token” is logged, but when actually invoking the web-socket connection request, the request header is not updated.

Has anyone faced this issue?
I got few articles that this is chrome bug, is this fixed yet?


function updateTokenRule(token) {
  const rule = {
    id: RULE_ID_TOKEN,
    priority: 1,
    action: {
      type: "modifyHeaders",
      requestHeaders: [
        {
          header: "token-header",
          operation: "set",
          value: token,
        },
      ],
    },
    condition: {
      urlFilter: "wss://localhost:19457/",
      // resourceTypes: ["websocket"],
    },
  };

  chrome.declarativeNetRequest.updateDynamicRules(
    {
      removeRuleIds: [RULE_ID_TOKEN],
      addRules: [rule],
    },
    () => {
      if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError);
      } else {
        console.log("Token rule updated with new token:", token);
      }
    }
  );
}

Looking for a State timeline chart from javascript code

I am interested in finding some kind of JS code for making a State timeline chart in javascript.
I know that Grafan has a really nice solution for this, so its some thing smililar.
I have like an array of data that has different values depending on the state of the machine.

Does anyone know if there is something out there that i can use.

Thanks alot.

How to remove multiple values in array. tried for loop already

I was playing around with bind function mainly and i decided to test out in removing all items at once in the ItemsinCart array when click the checkout button. it works by using pop function but when i tried for loop it does not work. this is the portion of the function where i also changed to for loop.

please advise how can i achieve it.

    <h1>The Books</h1>
    <div id="bookstore"></div>
    <h1>Your Cart</h1>
    <div id="cart"></div>

  <script>
  const bookstore = {
    books: ["Java", "Python", "JavaScript"],
      removeBook(title) {
      let newList = this.books.filter((book) => book != title);
      this.books = newList;
      this.displayBookstore();
  },

  displayBookstore() {
    const renderTarget = document.getElementById("bookstore");
    const bookList = this.books.map((book) => `<p>${book}</p>`);
    renderTarget.innerHTML = bookList.join("");
    shoppingCart.displayCart(this.removeBook.bind(this));
   },
  };

  const shoppingCart = {
    itemsInCart: ["Python", "Java"],
    handleClick(remove) {           //this is the section where i tried for loop.
    remove(this.itemsInCart.pop());
 },

  displayCart(clickHandler) {
    const renderTarget = document.getElementById("cart");
    const itemsInCart = this.itemsInCart.map((item) => `<p>${item}</p>`);
    const checkoutButton = "<button id='checkout'>Check Out</button>";
  renderTarget.innerHTML = itemsInCart.join("") + checkoutButton;
  document
 .getElementById("checkout")
 .addEventListener("click", () => this.handleClick(clickHandler));
    },
  };
  bookstore.displayBookstore();
</script>

Issue with Local Audio Playback in Custom Video Call Demo

I’m working on a custom video call demo using Daily’s call object mode with SvelteKit. The audio from the shared video is correctly sent to other participants, but it doesn’t play locally. If I join the same room using the Daily.co website, the audio plays correctly.

Here are the relevant code excerpts:

VideStreamerTile.svelte:

let videoInput;
let localVideoStream;
let localAudioStream;

function playLocalVideoFile(evt) {
    let videoEl = document.getElementById('local-vid');
    let file = evt.target.files[0];
    if (!videoEl.canPlayType(file.type)) {
        toast('cannot play that file');
        return;
    }
    videoEl.src = URL.createObjectURL(file);
    videoEl.play().then(() => {
        localVideoStream = videoEl.captureStream();
        if (localVideoStream) {
            localVideoStream = new MediaStream(localVideoStream.getVideoTracks());
        }
        const audioTracks = videoEl.captureStream().getAudioTracks();
        if (audioTracks.length > 0) {
            localAudioStream = new MediaStream(audioTracks);
        }
    });
}

async function shareVideo() {
    if (localVideoStream) {
        const combinedStream = new MediaStream([
            ...localVideoStream.getVideoTracks(),
            ...(localAudioStream ? localAudioStream.getAudioTracks() : [])
        ]);
        await callObject.startScreenShare({
            mediaStream: combinedStream,
            videoSource: 'mediaStream',
            audioSource: localAudioStream ? 'mediaStream' : false
        });
    } else {
        toast('No video stream available to share.');
    }
}

VideoTile.svelte:

let videoTrackSet = false;
let videoSrc;
$: videoTrack = participant?.tracks?.video;
$: screenTrack = screen?.tracks?.screenVideo;
$: {
    if (!screen && videoTrack?.state === 'playable' && !videoTrackSet) {
        videoSrc = new MediaStream([videoTrack.persistentTrack]);
        videoTrackSet = true;
    } else if (screen && screenTrack?.state === 'playable' && !videoTrackSet) {
        videoSrc = new MediaStream([screenTrack.track]);
        videoTrackSet = true;
    }
}

let audioTrackSet = false;
let audioSrc;
$: audioTrack = participant?.tracks?.audio;
$: {
    if (audioTrack?.state === 'playable' && !audioTrackSet) {
        audioSrc = new MediaStream([audioTrack.persistentTrack]);
        audioTrackSet = true;
    }
}

function srcObject(node, stream) {
    node.srcObject = stream;
    return {
        update(newStream) {
            if (node.srcObject != newStream) {
                node.srcObject = newStream;
            }
        }
    };
}

Any insights or suggestions on how to resolve this issue would be greatly appreciated!

Thanks in advance!

Building and loading a React Component from a bundle is file

I have not seen any implementation of this but is it possible to build a React component into a bundle js file through Vite then load the component from the bundle js file into another application?
Such that the other application can pass props to the loaded component and also re-render when the content in the other application loads.

Problem with recursion interfering with a for loop iterating over a nested array in JavaScript

I have a function in my JavaScript code which iterates over an array called background_check which has elements which are also arrays. I want to see if any element in this nested array is a 0 (each element is either a 0 or a 1). I do this with a for loop iterating over the array and calling the function recursively if any element is an array.

Here is my code:

function loop_checker(background_check) {
    let loop_condition = false
    let count = background_check.length
    for (i=0;i<count;i++) {
        if (typeof background_check[i] === 'object') {
            let x = loop_checker(background_check[i])
            if (x === true) {
                loop_condition = true
            }
        }
        else if (background_check[i] === true) {
            loop_condition = true
        }
    }
    return loop_condition

The array in question is background_check = [1, 1, 1, 1, [1, 1, [1, 0]]]
The function iterates over the first four elements fine. It then gets to the i=4 case and iterates over the smaller array. When the new for loop gets to i=2 it iterates over the smallest list. Once it is all done it goes back down the call stack, but once it gets back to the first call of the function, i=4 has changed to i=3 and so it redoes the 5th element. This repeats infinitely; I cannot figure out why this has happened. I think it may be an issue with the scope of the i variable and recursion messing with that, but I am very new to JS.

P.S. sorry if this is poorly or incorrectly formatted, this is my first question. Thanks in advance!