Re-render only part of the component

I have SVG map where i want to display some tooltip when user hovers the element:

const Tooltip = ({ children }) => {
    return (
        <div className="Tooltip">
            <div className="Tooltip--content">
                {children}
            </div>
        </div>
    );
}

export default Tooltip

and component

const svgField = () => {
    const tooltip = useRef(null);
  // methods

    const FieldWrapper = styled('div')(({ theme }) => ({
        width: '100%',
        height: '100%',
        position: 'relative',
        /* display */
        overflow: 'hidden',
        '&':{
            'alignItems': "center",
            'justifyContent': "center"
        },

        [theme.breakpoints.up('xs')]: {
            display: 'none'
        },
        [theme.breakpoints.up('lg')]: {
            display: 'flex'
        },
    }));

    return (
        <FieldWrapper >
            <div ref={tooltip} style={{position: 'absolute', display: 'none'}}>
                <Tooltip>
                    {currentTooltipInfo}
                </Tooltip>
            </div>
            <svg className="Field--svg"
                 width={fieldSize[0]}
                 height={fieldSize[1]}
                 sx={{
                     'padding-top':'12px'
                 }}
            >
                <g className="field">
                    {
                        fields.map((d, i) => (
                            <path
                                // 
                                onMouseMove={(e) => handleMouseMove(e, d)}
                            />
                        ))
                    }
                </g>
            </svg>
        </FieldWrapper >
    )
}

now if i use hooks , e.g:

 const [tooltipContent, setTooltipContent] = useState(null);

and implement handleMouseMove such as:

const [tooltipContent, setTooltipContent] = useState(null);


const handleMouseMove = (evt, country) => {
    tooltip.current.style.display = "block";
    tooltip.current.style.left = evt.clientX + 10 + 'px';
    tooltip.current.style.top = evt.clientY + 10 + 'px';
    tooltip.current.style.border="1px solid black";

    setTooltipContent("Some content");
}

wouldnt this re-render whole component including SVG ( which is not small ) and thus affect performance while i need only to re-render tooltip element?

Is there a way how to rerender only tooltip element? I am not proficent in React so every piece of information is appreciated.

Thanks.

WebRTC mixing two audio streams with AudioContext

I’m using mediasoup and webrtc to create media streams.

async consume(transport) {
        const { rtpCapabilities } = this.device;
        const data = await this.socket.request('consume', { rtpCapabilities });
        const {
            producerId,
            id,
            kind,
            rtpParameters,
        } = data;

        

        //Get playerID
        let playerID = await this.socket.request('getPlayerID', id);
        playerID = parseInt(playerID, 10);

        

        let producerIDS = await this.socket.request('getProducerIDS', id);
        let consumerIDS = await this.socket.request('getConsumerIDS', id);

        console.log("producerIDS", producerIDS);
        console.log("consumerIDS", consumerIDS);

        let codecOptions = {};
        const consumer = await transport.consume({
            id: id,
            producerId: producerId,
            kind: kind,
            rtpParameters: rtpParameters,
            codecOptions: codecOptions,
        });
        
        console.log("First producer ", producerIDS[0]);
        console.log("Current producer ", producerId);
        console.log("Consumer ID", id)
        console.log("Player ID:", playerID);
        console.log("Consumer1", consumer, consumer.track);
        //stream.addTrack(consumer.track);

        let audioTracks = [];
        audioTracks.push(consumer.track);

        if (playerID === 2 && producerIDS.length === 2) {
            const data1 = await this.socket.request('consume2', { rtpCapabilities });

            console.log("Data: ", data);
            console.log("producerId: ", data.producerId);

            const consumer2 = await transport.consume({
                id: data1.id,
                producerId: data1.producerId,
                kind: data1.kind,
                rtpParameters: data1.rtpParameters,
                codecOptions: codecOptions,
            });

            console.log("Second producer", data1.producerId);
            console.log("Consumer2", consumer2, consumer2.track);
            audioTracks.push(consumer2.track);
            //stream.addTrack(consumer2.track);
        }

        console.log("Audio Tracks: ", audioTracks);
        
        //const sources = audioTracks.map(t => ac.createMediaStreamSource(new MediaStream([t])));

        //var dest = ac.createMediaStreamDestination();
        //var aud1 = ac.createMediaStreamSource(s1);
        //aud1.connect(dest);
        

        
        
        //sources.forEach(s => s.connect(dest));

        //console.log(dest.stream.getAudioTracks());
        //stream.addTrack(dest.stream.getAudioTracks()[0]);
        //stream = dest.stream;

        /*
        let stream = new MediaStream();
        if (audioTracks.length <= 1) {
            stream.addTrack(audioTracks[0]);
        }
        else {
            stream.addTrack(audioTracks[1]);
        }
        */

        let stream = new MediaStream();
        if (audioTracks.length <= 1) {
            stream.addTrack(audioTracks[0]);
        }
        else {
            const ac = new AudioContext();
            const dest = ac.createMediaStreamDestination();
            let aud1stream = new MediaStream();
            aud1stream.addTrack(audioTracks[0]);
            let aud2stream = new MediaStream();
            aud2stream.addTrack(audioTracks[1]);
            const aud1 = ac.createMediaStreamSource(aud1stream);
            const aud2 = ac.createMediaStreamSource(aud2stream);
            var gain = ac.createGain();
            gain.gain.value = 10;
            gain.connect(dest);
            aud1.connect(dest);
            aud2.connect(dest);
            stream = dest.stream;
        }

        console.log("Stream tracks: ", stream.getAudioTracks());
        return stream;
        
    }

I’m attempting to mix two streams together here.

else {
            const ac = new AudioContext();
            const dest = ac.createMediaStreamDestination();
            let aud1stream = new MediaStream();
            aud1stream.addTrack(audioTracks[0]);
            let aud2stream = new MediaStream();
            aud2stream.addTrack(audioTracks[1]);
            const aud1 = ac.createMediaStreamSource(aud1stream);
            const aud2 = ac.createMediaStreamSource(aud2stream);
            var gain = ac.createGain();
            gain.gain.value = 10;
            gain.connect(dest);
            aud1.connect(dest);
            aud2.connect(dest);
            stream = dest.stream;
        }

However the stream indicates that it is streaming but no audio can be heard. I’d appreciate any help all I want is to mix the two streams. If AudioContext doesn’t work does anyone have advice on using Gstreamer to mix the audio or something else? Thanks.

How to add an array as a key to a set in Javascript?

Sorry if this is a duplicate. I’m looking for the best way to convert an array into a key I can use for a set in JavaScript.

const set = new Set()
const arr = [1,0,-1]
const arr2 = [1,0,-1]
set.add(arr)
set.add(arr2)

This should work because both arr and arr2 are different objects and the set recognizes their references as unique. What’s the best way I can convert arr and arr2 into keys so the set recognizes them as unique?

I tried doing JSON.stringify(arr), but I had difficulty converting them back into number[].

Any help is appreciated!

Next-auth CredentialProvider config and redirect

I’m a bit confused on the implementation of the credentials provider and the redirects. The documentation says that the credentials provider doesn’t support a callback and its for the OAuth providers. This is fine. However, instead of staying on the page and flashing an error message or even logging in like in this video it redirects to https://localhost/api/auth/callback/[credentials-provider-name]. Which doesn’t even include the port I’m working with. If I explicitly set an id it uses that at the end of the url in instead.

This is what I have for the provider

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    CredentialsProvider({
      credentials: {
        username: { label: "Username", type: "text", placeholder: "someuser69" },
        password: { label: "Password", type: "password" },
      },
      name: "User Pass",
      type: "credentials",
      async authorize(credentials, req) {
        // Add logic here to look up the user from the credentials supplied
        // if ("deeswoc".localeCompare(credentials.username) && "12345678".localeCompare(credentials.password)) {
        return {
          id: 2,
          name: "user",
          email: "[email protected]",
        }
        // }
        return null;
      }
    })
    // ...add more providers here
  ],
  callbacks: {
    async jwt({ token, account }) {
      // Persist the OAuth access_token to the token right after signin
      if (account) {
        token.accessToken = account.access_token
      }
      return token
    },
    async session({ session, token, user }) {
      // Send properties to the client, like an access_token from a provider.
      session.accessToken = token.accessToken
      return session
    },
    async redirect({ url, baseUrl, }) {
      console.log("");
      return baseUrl;
    },
    async signIn({ user, account, profile, email, credentials }) {
      return '/home';
    }
  },
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60,

  },
  secret: "CHANGE!!!",
  jwt: {
    maxAge: 60 * 60 * 24 * 30,
    secret: "afdsfi",

  },

})

I’ve looked through the docs and I’m not sure if I’m making some massive oversight, here. But some of my major confusions are:

  • Where is this callback set and how do I turn in off in the default provider (if possible).

  • I don’t think the authorize function works. If I put a console log in it. It doesn’t print to the terminal. So I don’t even know if it’s being called.

how to deploy a vanilla js web application

, i am creating a the front end part of a project that i am doing and i have some questions about deploying a vanilla js app.

i am using webcomponentes with the shadow dom to create componentes for my project but since i am only using vanilla js – html -css without frameworks i wanna know if is possible to configure a image with docker and then upload that image to a custom server and deploy it then ? i dont know if you could give me some tips or some documentation on how to do the deploy process of a vanilla app, or how to do the deploy using docker with kubernetes.

Also wanna know if using webpack with babel loader can be of any help in terms of performance if i am using only vanilla js with webcomponents.

thanks in advance

Regex for First and Last name possible middle with possible characters inbetween

I’m trying to create a Regex for getting First and Last Name with possible middle name. I have a database that contains First and Last but not always the middle name.

For example, the user may input ‘john ray smith’ but my database will have “John Smith”. It’s also possible that my database has ‘John Ray Smith’ but the user inputs ‘John Smith’. Another that may be possible is the user inputs ‘John.Ray.Smith2456’. But I would only want to extract ‘John Ray Smith’.

If Statement with regex test is not working if included console.log before the statement [duplicate]

Following is my code which is giving weird output.

// Count Consonants in a string

function countConsonants(str = '') {
  const regex = /(?![aeiou])[a-z]/gi;
  let len = 0,
      strLen = str.length;
  
  for(let i=0; i< strLen; i++) {
    console.log(`${str[i]} === ${regex.test(str[i])}`);
    if(regex.test(str[i])) {
      console.log(`Inside Len ${len}`)
      len++;
    }
  }
  return len;
}


console.log(countConsonants('abc de')) // Expected output - 3 but returning 0

Issues –

Here the length returned as 0 though it should return 3. Weird thing is if I remove the console.log from the above code, it will return an output of 2 which is again wrong but a different value.

Let me know what I am doing wrong here and concept I missed.

Can’t make pyramid of numbers

Need to get:

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

My code:

function getPyramid() {
let nums = 0;
for (let i = 1; i <= 15; i++) {
      for (let n = 1; n < i; n++) {
   console.log(n);

}
   console.log('<br/>');

}
return nums;
}
getPyramid();

MaterializeCSS input date displaying prior day

When I show an input field with datepicker passing in a value from my SQL data, MaterializeCSS is displaying the value as the day before. It works if I reformat the date using slashes instead of dashes, but that is a horrible long-term solution.

Here is the code:

<input type="text" class="datepicker" value="2022-03-15">

Which will show as March 14th in MaterializeCSS and if you save, it saves it as March 14th.

Here is the CodePen showing the incorrect behavior.

https://codepen.io/programminglabs/pen/ExQxNvx

There must be a setting in JS in MaterializeCSS but I cannot find it. I expect the issue is I need to add one microsecond. How can I do that globally in my MaterializeCSS environment?

XMLHttpRequest is not defined in frontend code

I get this error from

<script lang="ts">
    import { onMount } from "svelte";

    const xhr = new XMLHttpRequest();

    let url = "";

    onMount(() => url = window.location.href.substr(31)); //get query

    xhr.open("GET", url);

    xhr.onload = () => {
        let resp = xhr.response;
    }

    xhr.send();
</script>
{resp}

the error is

ReferenceError: XMLHttpRequest is not defined

I am using svelte, and all the questions about this error are about backend node.js code.

How to pass id parameter in react-router-dom v6?

I’m trying to pass an id in a path to a component. Here is my route-config.ts file:

...
import EditMovie from "./movies/EditMovie";

const routes = [
   ...
  {path: '/genres/edit/:id(\d+)', component: EditGenre},
...
];

export default routes;

And the component file that isn’t loading EditGenre.tsx:

import { useParams } from "react-router-dom"

export default function EditGenre(){
  const {id}: any = useParams();
  return (
    <>
      <h3>Edit Genre</h3>
      The id is {id}
    </>
  )
}

The other pages (routes) work fine, even “http://localhost:3000/genres/edit”, except when I go to “http://localhost:3000/genres/edit/12” I get error:

No routes matched location "/genres/edit/12" 

And nothing loads below the nav bar.

I’m following the code from someone using react-router-dom v5 and am guessing it’s changed in v6?