How to use dynamic head in Next js 13?

before next js 13 we used to do dynamic head as an import. but in Next JS 13 they introduced the head.js class. this works when using a static page, but when loading a dynamic how can we change the title and desc in the head? i directly imported the next/head and then assign the data but it didn’t change the head.

export default function DetailPage({ params: { itemid } }) {

const [datas, setDatas] = useState({});

  const getData = async () => {
    const docRef = doc(db, "items", itemid);
    const docSnap = await getDoc(docRef);
    setDatas(docSnap.data());
  };

  useEffect(() => {
    if (Object.keys(datas).length == 0) {
      getData();
    }
  }, [datas]);

return (

<>
<Head>
        <title>{datas.title}</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <meta
          name="keywords"
          content="some contents"
        />
        <meta
          name="description"
          content={datas.desc}
        />
      </Head>

  <section>...</section>

</>

)

}

Javascript / Angular JS 1.x : Promise Cause Infinite Loop

The code below is a function that’s called to enable/disable an html element in an AngularJS application. The issue is that when this code runs it gets stuck in an infinite loop on the line with await.

In fact, it’s stuck on the same line of data (the parameter), i.e., when this code runs, as soon as the line with await executes, it jumps right back to the function call itself.

Any ideas as to why this behavior is happening?

async function isXaasFieldDisabled(line) {
  let disabled = true;
  const _mfg1 = 'XXXXX';
  const _mfg2 = 'YYYYY'; 

  if (line.productPrice.manufacturerName.toUpperCase() === _mfg1) {
      disabled = false;
  } else if (line.productPrice.manufacturerName.toUpperCase() !== _mfg2) {
      const product = await CatalogService.getProduct(line.productPrice.productId);
      disabled = !!_.find(product.attributeValues, v => v.productAttribute.name.toUpperCase() === 'ABC123');
  }
  console.log(disabled);

  return disabled;
}

Mock custom global window variable for individual tests with Jest

I’m trying to mock a custom global window variable for an individual test. Here’s a sandbox to the test that demonstrates the issue.

I have a React component MyComponent.tsx that references a global window variable from index.html (from the server).

// index.html
<script>
 var globalVars = {
   myVar: "value"
 };
</script>
// MyComponent.tsx
function MyComponent() {
 const { myWindowVar } = constants;
   return <h1>{myWindowVar}</h1>;
}
// constants.ts
const constants = {
  myWindowVar: window?.globalVars?.myVar
};

I’ve tried a few methods to mock this variable but it doesn’t seem to be applied before MyComponent is rendered and the test fails.

// MyComponent.test.js
test("Test mocked window variable", () => {
  // 1. trying to mock the global/window object directly doesn't work
  // global.globalVars = { myVar: "mocked value" };

  // 2. also does not work
  // Object.defineProperty(window, "globalVars", { myVar: "mocked value" });

  // 3. spying on the window object and updating with new
  // variable doesn't work either
  const originalWindow = { ...window };
  const windowSpy = jest.spyOn(global, "window", "get");
  windowSpy.mockImplementation(() => ({
    ...originalWindow,
    globalVars: { myVar: "mocked value" }
  }));

  render(<MyComponent />);

  expect(screen.getByText("mocked value")).toBeInTheDocument();

  windowSpy.mockRestore();
});

Is this possible? How can I mock this custom window variable for individual tests with Jest before the component is rendered?

Find minimum values of length, width and height for pack of several itmes with various dimensions [closed]

We have several items (values are random):

items = [
  {length: 1, height: 2, width: 3},
  {length: 7, height: 5, width: 2},
  {length: 2, height: 4, width: 6},
  {length: 3, height: 2, width: 4},
  {length: 4, height: 1, width: 2},
]

And we have 3 types of pack:

pack1 = {length: 3, width: 2, height: 2}
pack2 = {length: 5, width: 2, height: 2}
pack3 = {length: 7, width: 3, height: 3}

The goal is to get minimums of length, width and height of the pack (wich 1 one will fit among 3 packs)that can fit to put all those items. Items can be rotated, placed one above another and so on.
Is there any library that can calculate those dimensions or maybe any other solution on javascript/node.js?

how to convert svg path to glyph path code

I have this type of icons in my website

<glyph unicode="&#xe908;" glyph-name="fb" horiz-adv-x="532" d="M531.692 789.858h-96.886c-78.769 0-89.797-36.234-89.797-89.009v-115.791h180.382l-23.631-181.957h-157.538v-467.102h-186.683v467.102h-157.538v181.957h157.538v134.695c-0.652 6.351-1.023 13.724-1.023 21.183 0 121.373 98.393 219.766 219.766 219.766 6.182 0 12.305-0.255 18.358-0.756 1.311 0.066 3.801 0.074 6.293 0.074 46.065 0 91.527-2.583 136.248-7.611z" />

I am trying to add more icons but my icons are SVG, my website accept glyph path, so I have to convert my svg to glyph

Standrad SVG path is not working

RegEx to replace anything except positive number (no decimals)

I am looking for a very specific RegEx with the following capabilities:

  • Remove any leading zero
  • Remove anything that is not a number
  • Remove anything after decimal comma or decimal point

Here are some examples:

"1,1" => "1"
"1,5" => "1"
"1.1" => "1"
"1.5" => "1"
"-1" => "1"
"a-1" => "1"
"+1" => "1"
"a+1" => "1"
"01" => "1"
"1+1" => "1"
"abc" => ""
"abc1" => "1"

The one I was able to construct was not able to handle all my needs:
/[^0-9].*/g

Migrate React Native Project for Web also using same code using React Native Web

My task is to add web support in existing react-native project using react -native-web package
But I am getting issues for those packages that does not have support in web like “ActionsheetIos is not exported”.

If this type of component is used inside my react native code component, I can simply create new file .web.ts extension and export empty object from it.
Then error goes away, but what should I do when same error comes inside my ** node_module** folder dependencies code.

How to handle this case.

Currently , I am following CRA create react approach inside react native web…adding CRA scripts in react native code and running web from it.

Any idea how to tackle this issue and also is my approach is fine?

I checked for multiple online solutions but could not find right direction

Laravel, Livewire, @vite, add specific JS on the layout

I’m learning Livewire, and I’m using Laravel with Vite and Bootstrap CSS.

Currently, my page is a full Livewire component, and its view is located at “resources/views/livewire/adm/profile.blade.php“. I’m using a layout called “primal”.

Here’s the render function of my Livewire component:

    public function render()
    {
        return view('livewire.adm.profile')
            ->extends('layouts.primal');
    }

This is my “primal” layout:

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <style>

    </style>
    @vite(['resources/js/adm.js'])
    @livewireStyles
</head>
<body>
    @yield('content')
    @livewireScripts  
</body>
</html>

And this is my “adm.js” file:

// Import our custom CSS - (bootstrap css)
import '../scss/adm.scss'

// Import all of Bootstrap's JS
import * as bootstrap from 'bootstrap'
window.bootstrap = bootstrap;

// profile page
const toastLiveExample = document.getElementById('liveToast')

const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
window.addEventListener('notify', () => {
    toastBootstrap.show()
})

Currently, everything is working fine, and I can display a Toast message. However, I would like to be able to load the JavaScript that is specific to each component dynamically.

Currently, if I want to use my “primal” layout for another Livewire component, it will load the JavaScript for the “profile” page.

Is it possible to achieve something like this inside my layout, where I can change the value of “specific_js_for_the_component.js” dynamically?

@vite(['resources/js/adm.js','resources/js/specific_js_for_the_component.js'])

Or is there another option to achieve this?

Thank you for your help. Please excuse any mistakes in my English .

React Leaflet update position

I’ve got a question about React Leaflet. I am now trying to build a PWA with the react framework and I need to use a map, hence React Leaflet.

So here’s the situation :

I need to load the Map when I go on the map page and it must be at the current location I am in. I made a Map component that is on the App.js file :

function App() {
  return (
    <Map />
  );
}
export default App;

In my Map component, I currently don’t have much because I changed lots of things that didn’t work.

function Map() {
  
    return (
      <>
        <MapContainer center={[46.8182, 8.2275]} zoom={12} scrollWheelZoom={true}>
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <ResetView />
        </MapContainer>
      </>
    )
  }

export default Map;

I looked at all those websites and tried understanding how to do it but never really got anything right :

https://react-leaflet.js.org/docs/example-animated-panning/

https://react-leaflet.js.org/docs/example-external-state/

https://www.reddit.com/r/reactjs/comments/qol90a/set_position_of_the_react_leaflet_map/

So what I would like to do is to get the current location with this :

navigator.geolocation.getCurrentPosition();

And when the current location returns the longitude and latitude, to pan the map to where those coordinates are.

I hope I was clear enough and thank everyone for any kind of help !

I tried to send the location through props. I tried to get the location and load the Map component through React hooks but nothing seemed to work.

Why my element undefined in code but defined if I run the code in console js? [duplicate]

I’m trying to add a button to an element on YouTube with the following code:

document.addEventListener('DOMContentLoaded', function() {
  let elm = document.getElementsByClassName("style-scope ytd-guide-section-renderer")[8];
  let nbutton = document.createElement("button");
  elm.append(nbutton);
}, false);

Unfortunately, I’m always getting the error:

cannot read properties of undefined (reading ‘append’)

When I run the code in console, after the page is loaded, everything works fine.

I thought, the problem is, that the page isn’t fully loaded before I’m trying to access the element, so I added a page load event listener, but It’s still not working.

Keep getting undefined from calling api via reduxjs createApi

I am calling an API using createApi that somebody created.
const {result, isSuccess} = useCallAnApi(item.id);
The above I do inside a function – function getByItem(item);
Then I try to access the ‘result’. If I console.log it, I get a couple unfinished ones and than finally a successful result with all the data. But if instead of logging it I try to access ‘result’ like this result.data. I always get undefined. I tried accessing it inside useEffect(, [isSuccess]) but I get undefined anyway.
This is the current attempt, where I get undefined:

function getByItem(item) {
    const {result, isSuccess} = useCallAnApi(item.id);
    useEffect(() => {
       if (isSuccess) {
         const data = result.data.data;
         // some filtering logic
         return data;
      }
    }, [isSuccess])
}

I get undefined immediately on ‘result.data’ right after if condition.

I tried all possible if conditions and solutions in general that I found on stackoverflow.

Javascript array starts with a comma?

I was solving this problem on leetcode, and it appears that I found a good solution. The algorithm has to return an array of running sum. For example, if input is nums [1,2,3,4] the output must be [1,3,6,10]. My algorithm seems to be working fine, however the output starts with a comma and I can’t get it done.

Here is my algorithm:

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var runningSum = function(nums) {
  let output = new Array(nums.length)
  var sum = 0;
  for (let i = 1; i < nums.length + 1; i++) {
    sum = sum + nums[i - 1];
    output[i] = sum;
  }
  return output;
};

When given [1,2,3,4] it returns [,1,3,6,10] and I can’t understand why there is a comma at the beginning of the output array and how to make it right.