Pass data in livewire component with javascript

I have datepicker with custom attribute.
i give this attribute with javascript and i try to pass this att with javascript to my livewire controller.

 <input id="birth-date" type="text"  autocomplete="off" placeholder="dd/mm/yyyy" class="form-control air-datepicker" data-position="bottom right" />

 <i class="btn btn-primary btn-sm text-light " id="date_start_btn" onclick="startday()">save date</i>

<script>
function startday() {
var startday = document.getElementById('birth-date').getAttribute('data-jdate');
document.getElementById('birth-date').value = startday;
document.getElementById('date_start_btn').classList.remove("btn-primary");
document.getElementById('date_start_btn').classList.add("btn-success");
}
                        </script>

i want to send startday to my livewire component to use

Can I show projects in my resume where I worked as a team member member but the project is not hosted on my GitHub

Me and my friend created a group project .but the problem is i don’t have that project on my GitHub,all work I did is on my friends GitHub ,it shows me as a contributor so can I still add it in my resume ? Or will I have to upload it separately on my GitHub but the problem would be that it won’t show my merges and all so will it cause a problem?
If yes how can i show it in my resume?

How do I show Google Sheet embeds on an interactive SVG?

I’m trying to create an interactive SVG map, and if you click an item, a table about that item pulled from Google Sheets will appear. Each items have their own set of data. How do I achieve this? My current idea right now is to prepare iframes on respective tables, set them to hidden, and show them when the corresponding item is clicked. Will it even work, and is there any simpler way to do so?

i cant play music in js when i put it in if

i have variable equals “new Audio(src)”. but when i play this it give err.

code : if (document.getElementById("play").value === "true") { music.play(); }

play is a select from html

it is err: Uncaught (in promise) DOMException: The element has no supported sources.

Client’s webcam produces broken images in a web app [closed]

In our web app, users are required to have their webcam open, and we take periodic pictures of them during a session via their webcam. We store these pictures in Firebase, and create urls for later use.

For one client’ session, all of their webcam photos seems to corrupted, and I wonder what could be the reason. I know that their webcam stream was working, and our system was able to take pictures from their stream and create urls for them. However, when I try to open any of these urls, I only see a 9 byte jpg file, and Windows photos says “It appears that we don’t support this file format”.

How do I load Next.js App after promise is resolved?

How do I achieve the code below using Next.js.

I believe there is an issue with Next.js not being able to access the window object unless you’re inside a useEffect(() => {}) hook.

Changing to regular React, this code worked fine.

What am I missing in the Next.js ecosystem that doesn’t allow this type of delayed render to work?

Thank you.

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { initializeContract } from "./utils/near";

window.nearInitPromise = initializeContract()
  .then(() => {
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById("root")
    );
  })
  .catch(console.error);

reportWebVitals();

Return value from Opentype.js load function – ReactJS

I am using Opentype.js to convert my text strings to SVG Path, so i can get the length of path. I am trying to use that opentype.js function as a helper, so i can import & call it in my code anywhere, this way i don’t have to write that code again and again to convert text to svg path.
Here is my code:

export function textToPath(text, size) {
    // Variable to store length
    let length = 0
    const fontFile = "https://fonts.gstatic.com/s/firasans/v15/va9E4kDNxMZdWfMOD5Vvl4jO.ttf"
    let params = {
        string: text,
        font: fontFile,
        fontSize: size,
        decimals: 1,
        singleGylyphs: false
    }
    opentype.load(params.font, function (err, font) {
        if (err) {
            console.error(`font couldn't be loaded`);
            return false;
        }

        let options = params.options;
        let unitsPerEm = font.unitsPerEm;
        let ratio = params.fontSize / unitsPerEm;
        let ascender = font.ascender;
        let descender = Math.abs(font.descender);
        let ratAsc = ascender / unitsPerEm;
        let ratDesc = descender / unitsPerEm;
        let yOffset = params.fontSize * ratAsc;
        let lineHeight = params.fontSize + params.fontSize * ratDesc;
        let singleGylyphs = params.singleGylyphs;

        // get glyph data
        let teststring = params.string.split("");

        let glyphs = font.stringToGlyphs(params.string);
        let leftSB = glyphs[0].leftSideBearing * ratio;
        let textPath = "";

        //individual paths for each glyph
        if (singleGylyphs) {
            let paths = font.getPaths(
                params.string,
                -leftSB,
                yOffset,
                params.fontSize,
                options
            );
            paths.forEach(function (path, i) {
                let pathEl = path.toSVG(params.decimals);
                textPath += pathEl.replaceAll(
                    "d=",
                    'class="glyph glyph-' + teststring[i] + '" d='
                );
            });
        }
        //word (all glyphs) merged to one path
        else {
            let path = font.getPath(
                params.string,
                -leftSB,
                yOffset,
                params.fontSize,
                options
            );
            textPath += path
                .toSVG(params.decimals)
                .replaceAll("d=", 'class="glyph" d=');
        }

        // render
        let fontSvgWrp = document.createElement("div");
        fontSvgWrp.classList.add("fontSvgWrp");
        let fontSvg = document.createElementNS(
            "http://www.w3.org/2000/svg",
            "svg"
        );
        fontSvg.classList.add("svgText");
        fontSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
        fontSvg.innerHTML = textPath;
        fontSvgWrp.appendChild(fontSvg);

        // adjust bbox
        let bb = fontSvg.getBBox();
        let stringWidth = Math.ceil(bb.width + bb.x);
        fontSvg.setAttribute("viewBox", "0 0 " + stringWidth + " " + lineHeight);
        fontSvg.setAttribute("width", stringWidth);
        fontSvg.setAttribute("data-asc", ratAsc);

        let textPathSvg = fontSvg.querySelector(".glyph");
        let textPathLength = textPathSvg.getTotalLength();

        // Assign the length to the variable
        length = textPathLength
    });
    console.log(length);
    // Return the length
    return length
}

Another file to call that helper function

const length = textToPath("Hello", 100)
console.log(length)
// It returns 0

If i console the length inside the opentype.load function, it is printing the correct length, but outside of the opentype.load function, it is printing 0 (the initial value). It is not updating my length attribute. Can someone please help me to achieve this?

Associate data from one array to another array

// This function should receive 2 arrays, and transform it into a single object, similar to columns and rows of a spreadsheet

// Sample array1: [“Name”, “Address”,”Zip Code”,”Phone”]

// Sample array2: [[“Manuel”, “Street 01”, “00414010”,”999918888″],[“Maria”, “Street 02”, “00414015”,”998818877″],[“Eduardo”, “Street 03”, “02614010”,”974640566″]]

// Sample expected output: [{Name: “Manuel”, Address: “Street 01”, Zip Code: “00414010”, Phone: “999918888”},{Name: “Maria”, Address: “Street 02″…}]

function arrayToObject(array1, array2) {
  
    const result = array2.map(row => {
        return row.reduce((obj, value, index) => {
            obj[array1[index]] = value;
            return obj;
        },{});
    });
}

the problem is that it returns me like this

{
  Name: "Manuel"
}
{
  Address: "Street 01",
  Name: "Manuel"
}
{
  Address: "Street 01",
  Name: "Manuel",
  Zip Code: "00414010"
}
{
  Address: "Street 01",
  Name: "Manuel",
  Phone: "999918888",
  Zip Code: "00414010"
}
{
  Name: "Maria"
}
{
  Address: "Street 02",
  Name: "Maria"
}
{
  Address: "Street 02",
  Name: "Maria",
  Zip Code: "00414015"
}
{
  Address: "Street 02",
  Name: "Maria",
  Phone: "998818877",
  Zip Code: "00414015"
}
{
  Name: "Eduardo"
}
{
  Address: "Street 03",
  Name: "Eduardo"
}
{
  Address: "Street 03",
  Name: "Eduardo",
  Zip Code: "02614010"
}
{
  Address: "Street 03",
  Name: "Eduardo",
  Phone: "974640566",
  Zip Code: "02614010"
}

Get nesxtjs Link tag from Backend

I have a project with react and next js. I have a simple page with the name X.content of this page coming from the backend (which means the backend sends me an HTML). On this page, I have several links. I want to know is it possible to send next link from the backend or I must use regular a tag for this situation.

Cannot Return Result from jQuery AJAX from a Function

I have a function using jQuery AJAX to return data from a data file. However, I cannot get the function to return the value. Any ideas?

    $(document).ready(function () {
        function getdata() {
            var result = 'default value';

            $.ajax({
                url: 'data/json/load.json',
                method: 'GET',
                dataType: 'json',
                success: function (response) {
                    result = response.data;
                    console.log('this is working and the result is: ' + result);
                    return result;
                }
            });

            return result;
        }

        var returndata = getdata();

        //I'm trying to return the results from my AJAX call here:
        console.log(returndata)
    });     

SWR not working properly with async fetch

Recently updated SWR – now for some reason my data is not fetching properly.

const { data: expressionsData, error: expressionsError } = useSWRImmutable(
       [`dashboard/expression/get-expression-analytics?startTime=${startDate}&endTime=${endDate}`, startDate, endDate],
       apiRequest
  );

Using this fetching,

import firebase from "./firebase";

export async function apiRequest(path, method = "GET", data) {
  const accessToken = firebase.auth().currentUser
    ? await firebase.auth().currentUser.getIdToken()
    : undefined;
    //this is a workaround due to the backend responses not being built for this util.
  if (path == "dashboard/get-settings") {
    return fetch(`/api/${path}`, {
      method,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${accessToken}`,
      },
      body: data ? JSON.stringify(data) : undefined,
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.error === "error") {
          throw new CustomError(response.code, response.messages);
        } else {
          return response;
        }
      });
  }
  return fetch(`/api/${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
    body: data ? JSON.stringify(data) : undefined,
  })
    .then((response) => response.json())
    .then((response) => {
      console.log("error", response);

      if (response.status === "error") {
        // Automatically signout user if accessToken is no longer valid
        if (response.code === "auth/invalid-user-token") {
          firebase.auth().signOut();
        }

        throw new CustomError(response.code, response.message);
      } else {
        return response.data;
      }
    });
}

// Create an Error with custom message and code
export function CustomError(code, message) {
  const error = new Error(message);
  error.code = code;
  return error;
}

// Check if a indexDb database exists
export function indexedDbdatabaseExists(dbname, callback) {
  const req = window.indexedDB.open(dbname);
  let existed = true;
  req.onsuccess = function () {
    req.result.close();
    if (!existed) window.indexedDB.deleteDatabase(dbname);
    callback(existed);
  };
  req.onupgradeneeded = function () {
    existed = false;
    callback(existed);
  };
}

Now I’m looking at this StackOverflow thread,

useSWR doesn’t work with async fetcher function

And thinking I’ll just remake the fetcher to be without Async. I’m just wondering why this has stopped working though in general, and if I can just keep my existing codebase.

The error is a 400 message, it only happens with this expressions API call which takes longer to load due to the amount of data I think,

 xxxx/dashboard/expression/get-expression-analytics?startTime=1648183720488&endTime=1650865720488 400 (Bad Request)

with error log

enter image description here

These calls are working fine, they have substantly less data though.

const { data: overall, error: psychometricError } = useSWRImmutable(
    `dashboard/psychometric/get-psychometric-home?starttime=infinite`,
    apiRequest
  );

  const { data: sentimentData, error: sentimentError } = useSWRImmutable(
     [`dashboard/sentiment/get-sentiment-timefilter?startTime=${startDate}&endTime=${endDate}`, startDate, endDate],
    fetchSentiment
  );

Parent route losing active state

I am currently using React Router Dom V6. I have a parent route with three child routes inside of it.

When I change the current acitve child, my parent link keeps losing active state.
I am using NavLink component for the parent as well as for the child links as well.

Below are excerpts from my codebase

Parent Link

                {menuItems.map(({name,key}) => (
                    <NavLink key={key} className={({isActive}) => isActive ? "font-bold text-white border-b-4" : "hover:border-b-4 ease-in-out duration-300"} to={handleNestedNavigation(key)}>
                        {name}
                    </NavLink>
                ))}
            </ul>```

Child Link

```<NavLink key={key} className={({isActive}) => isActive ? "font-medium mr-6 max-w-xs w-fit self-end text-black border-black border-b-2 pb-1" : "flex max-w-xs mr-6 pb-1 w-fit self-end hover:border-b-2 hover: border-black ease-in-out duration-100"} to={`/home/users/${key}`}>
                                {({isActive}) => (
                                    <React.Fragment>
                                        <span className="mr-1">{name}</span> 
                                        <span className={isActive ? "text-purple" : ""}>600</span>
                                    </React.Fragment>
                                )}
                            </NavLink>```

Any suggestions as to what am I doing wrong here? Or am I missing something?

Why do local variables persist between tests when using Mocha/Hardhat?

I’m writing unit tests using Mocha in Hardhat, and for some reason local variables declared in one test can be accessed in other tests. Here’s a very simple example:

describe("Example Test", function () {
    it("Test1", async function () {
        var1 = 1;
    });

    it("Test2", async function () {
        console.log(var1);
    });
}

Test2 will print ‘1’, even though I’m expecting a “not defined” error.

Is this a bug specific to Hardhat? I’m surprised I haven’t found any related questions to this on SO.