How to get cookie to pass it in header in next.js

I am using next.js app.
There is a fetch in the store, but it doesn’t work because it requires custom header with the value of a cookie.
So, there’s a clients cookie called ‘user_id’.
I am trying to fetch API from mobx store:

import { makeAutoObservable } from "mobx";

export class Tests {
    initState = [];

    constructor() {
        makeAutoObservable(this, {}, { autoBind: true })
    }    

    getRecommendations() {
        fetch(`/api/v4/tests`,{
            headers:{'X-Auth-token':'cookie_value_here'}
        })
        .then(res => res.json())
        .then(res => this.initState = res)
    }
}

export const instanceTests = new Tests();

So, my question is that i don’t understand how to pass client’s cookie value to this fetch.

I tried to get cookie in my index.tsx:

...
export const getServerSideProps: GetServerSideProps = async (context) => {
 const cookies = context.req.cookies;
 const token = cookies.user_id;

 return {
   props: {
     userToken: token
    }
  }
}

And now i’m stuck and can’t get how to achieve this cookie value inside the mobx store.

Javascript, checkbox and google sheets issue

Help me please
I’m using this code like a form forward to google sheet.
in this code i have 13 check box but when i submit is filled all “ch[]” in sheet, not one or two checked. Therefore i understood that each one ch[] have a value but how can i resolve this issue?
I need forward to the sheets just the checked boxes

<form 
     method="POST"
     action="https://script.google.com/macros/s/00000000000000000000000000000000/exec">

    <input type="text" required="" name="nome" placeholder="Digite seu Nome aqui">
    <input type="number" pattern="^d{11}$" required="" name="telefone" placeholder="DDD + Nº celular">
    <input type="e-mail" name="email" placeholder="Email (opcional)"><br><br>
    
        DIGITE SEU ENDEREÇO <input type="text" required="" name="endereço" placeholder="rua,nº,bairro cidade"><br>
    COPIE E COLE O ENDEREÇO DO MAPA <input type="url" name="end" placeholder="Localização (opcional)"><br><br>


    <label>HATCH <input type="checkbox" name="ch[]" value="60" /></label>
    <label>SEDAN <input type="checkbox" name="ch[]" value="60" /></label>
    <label>CROSSOVER <input type="checkbox" name="ch[]" value="60" /></label>
    <label>SUV <input type="checkbox" name="ch[]" value="60" /></label>
    <label>MINIVAN <input type="checkbox" name="ch[]" value="70" /></label>
    <label>PICUP <input type="checkbox" name="ch[]" value="70" /></label>
    <label>STATION WAGON <input type="checkbox" name="ch[]" value="70" /></label>
    <label>CONVERSÍVE <input type="checkbox" name="ch[]" value="70" /></label>
    <label>CUPE <input type="checkbox" name="ch[]" value="70" /></label>
    <label>LUXO <input type="checkbox" name="ch[]" value="70" /></label><br><br>
    
<p>ADICIONAIS</p><br>

    <label>LAVAGEM (SECO) DE MOTOR <input type="checkbox" name="ch[]" value="20" /></label>
    <label>CERA PLUS <input type="checkbox" name="ch[]" value="30" /></label>
    <label>CHEIRINHO <input type="checkbox" name="ch[]" value="10" /></label>
    

    <label>VALOR <input type="text" name="result" id="result" value="R$ 0,00" /></label><br>
    
    <input type="submit" value="ENVIAR">
    
</form>
</FONT>
</h2>



<script>
String.prototype.formatMoney = function() {
    var v = this;

    if(v.indexOf('.') === -1) {
        v = v.replace(/([d]+)/, "$1,00");
    }

    v = v.replace(/([d]+).([d]{1})$/, "$1,$20");
    v = v.replace(/([d]+).([d]{2})$/, "$1,$2");
    v = v.replace(/([d]+)([d]{3}),([d]{2})$/, "$1.$2,$3");

    return v;
};
String.prototype.toFloat = function() {
    var v = this;

    if (!v) return 0;
    return parseFloat(v.replace(/[D]+/g, '' ).replace(/([d]+)(d{2})$/, "$1.$2"));
};
(function(){
    "use strict";

    var $chs = document.querySelectorAll('input[name="ch[]"]'),
        $result = document.getElementById('result'),
        chsArray = Array.prototype.slice.call($chs);

    chsArray.forEach(function(element, index, array){
        element.addEventListener("click", function(){
            var v = this.value,
                result = 0;
            v = v.toFloat();

            if (this.checked === true) {
                result = $result.value.toFloat() + parseFloat(v);
            } else {
                result = $result.value.toFloat() - parseFloat(v);
            }

            $result.value = "R$ " + String(result).formatMoney();
        });
    });


}());

</script>

<script>


document.querySelector('#submit').addEventListener('click',function(){
 let cliente = document.querySelector('#nome').value;
 let sobrenome = document.querySelector('#sobrenome').value;
 let email = document.querySelector('#email').value;
 let telefone = document.querySelector('#telefone').value;
 let exampleFormControlSelect1 = document.querySelector('#exampleFormControlSelect1').value;

window.open(url);

});

</script>

My Website

sheets result

Wait for component mapping to complete before proceeding

We have a component which performs a map loop to create a list of components.
This list of components has some expensive calculations in there thus takes a while to create.

Trying to show a loading component while this map completes creating all the components.

Its not like I am making some async call to fetch data here to wait for it and show/hide loader.

It’s just the component taking time to create and looking to show a loader while it creates the list of components.

How could I show this loader, how to wait for the mapping to complete? Tried to play around with wrapping it inside a Promise.all but it complains that that is not a valid jsx.

import React from 'react';

const Main = ({items}) => {
  const [isLoading, setIsLoading] = useState(true); 

  /*
  // can't do this. It would become an infinite spinner
  if (isLoading) return <Loading />
  */

  return (
    <div>
      <Component1 />
      <Component2 />
      <div>
        {/* wait for this mapping to complete. Show a loader whiile it loads. setIsLoading(false) once done */}
        {items.map((item, i) => (<ExpensiveComponent/>))} 
      </div>
      <Component3 />
      <Component4 />
    </div>
  );
};

export default Main; 

Typescript: remove certain special chars from a string

I am trying to remove these special chars from a string < > : ; / ,

const afterReplace = fileName.replace(/[;:,<>\]/g, '');

This is working for all chars but for forward slash.

If I add forward slash in this (/[;:,<>/\]/g, '') and pass string 'Special/Name'. My output is just 'Special'. It truncates all chars after /.

const fileName = 'Special/Name'
const afterReplace = fileName.replace(/[;:,<>/\]/g, '');
console.log(afterReplace)

Use nodejs and require to download an image but ‘You need to enable JavaScript to run this app.’ error

I’m trying to automate the image download from my company dashboard.
My first idea was to use require.
I found a script that works perfectly: Downloading images with node.js
I get the following code:

var fs = require('fs'),
request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('done');
});

This code works without error and downloads the example image.
I modify it to add the headers (token,..) and the link of my image.
The script runs without errors but my contents are undefined:

content-type: undefined
content-length: undefined
done

When I look at the image created by the script, it contains html with the error “You need to enable JavaScript to run this app.”.
I have no idea how I can get around this problem. Does anyone have a tip?

Why are my swiper js slides very big and not showing the right amount I specified

I am trying to build a swiper slider with the following layout:

<div id="brokerCarousel" class="swiper">
    <div class="swiper-container">
        <div class="swiper-wrapper">
            @foreach($partners as $partner)
                <div class="swiper-slide">
                    <img src="{{ $partner->media('logo')->first() !== null ? $partner->media('logo')->first()->getUrl(800,600,'canvas') : '' }}" alt="{{ $partner->name }}">
                </div>
            @endforeach
        </div>
    </div>
</div>

I then have my JS code:

brokerCarousel() {
    if (document.getElementById('brokerCarousel')) {
        new Swiper('#brokerCarousel .swiper-container', {
            slidesPerView: 10,
            spaceBetween: 30,
            autoplay: {
                delay: 2500,
            },
            breakpoints: {
                576: {
                    slidesPerView: 2,
                },
                768: {
                    slidesPerView: 3,
                },
                1200: {
                    slidesPerView: 5,
                }
            }
        });
    }
}

Where I set slides to 5.

My scss:

#brokerCarousel {
    &.swiper{
        width: 100%;
        height: 100%;

        .swiper-container {
            max-height: 100%;
            .swiper-wrapper {
                .swiper-slide {
                    background-color: #fff;
                    padding: 30px;
                    border-radius: 10px;

                    img {
                        height: 200px;
                        width: auto;
                    }
                }
            }
        }
    }

}

But this is what my slides look like:

enter image description here

As you can see there are only two slides in view which is wrong by itself but they are also very wide. When I inspect the .swiper-slide in my inspector I see this style is applied: width: 1600px; margin-right: 30px;. My container is 1440px so one slide can never be 1600px when I have it set to 5.

What am I missing?

How to use environment file constant into firebase-service-worker.js

In my angular application, have added the firebase service worker functionality for the push notification. As currently I am maintaining the firebase setting at two place 1. environment.ts and 2. firebase-messaging-sw.js. Please refer the below settings that I am using in both file

 apiKey: 'samplekey',
authDomain: 'sampleDomain',
databaseURL: 'sampleDatabase url',
projectId: 'sample project id',
storageBucket: 'sample storage',
messagingSenderId: 'sample sender id',
appId: 'sample app id',
measurementId: 'sample value',

I want to maintain the above setting in environment.ts file only and want to access the setting in firebase-messaging-sw.js also from environment file, so please help me how can I achieve this.

fillRect not working when I have a lot of canvas elements

I have a Vue app where I want to perform fillRect on 10000 canvas elements.
It seems that when the number is really big the code doesn’t work anymore.
What can I do about this?

for (let key = 1; key <= 10000; key++) {
    let boxId = parseInt(key);
    let bridge = document.getElementById(boxId);

    if (this.scratched.scratchedValue.includes(boxId) == false) {
        let bridgeCanvas = bridge.getContext('2d');

        bridgeCanvas.beginPath();
        bridgeCanvas.fillStyle = "#b6b6b4";
        bridgeCanvas.fillRect(0, 0, bridge.width, bridge.height);
        bridge.style.opacity = '1';
        
    } else {
        bridge.style.opacity = '1';
        bridge.style.outline = '2px solid #ef7200';
    }
}

Update React to 16.8.0

I’m new to Javascript/TypeScript.
I just started working on a React TSX project. I tried to update React from 16.3.1 to 16.8.0 so I can use React hooks.

Therefore I executed npm install [email protected] [email protected] and npm install @types/[email protected] @types/[email protected] This worked fine and I did not get any errors.

After executin npm start I got the error .../node_modules/@types/prop-types/index.d.ts (33,47): Cannot find name 'T'. prop-types is not a direct dependency of my project. Therefore I don’t understand how I’m supposed to fix this. Have you any proposals how I should aproach this problem?

As far as I understand it it is an issue with TypeScript. because the error is in the @types directory. The Typescript version is 2.7.2.

Thanks for your help.

EasyAdmin – Add confirm modal on basic actions

I’m trying to update edit/new actions to get a confirmation modal but when I confirm into the modal window, the page page reload and nothing persist in the database.
Any solutions ?

ModuleCrudController (src/Controller/Admin/ModuleCrudController.php) :

public function configureActions(Actions $actions): Actions
    {
        return $actions
            ->update(Crud::PAGE_INDEX, Action::NEW,
            fn(Action $action) => $action
                ->setLabel('Ajouter un module'))
            ->update(Crud::PAGE_INDEX, Action::BATCH_DELETE,
            fn(Action$action) => $action
                ->setLabel('Supprimer'))
            ->update(Crud::PAGE_NEW, Action::SAVE_AND_ADD_ANOTHER,
            fn(Action $action) => $action
                ->setLabel('Créer et ajouter un nouveau module')
                ->displayAsLink()
                ->addCssClass('confirm-action')
                ->setHtmlAttributes([
                    'data-bs-toggle' => 'modal',
                    'data-bs-target' => '#modal-confirm',
                ]));

ModuleCrudController (src/Controller/Admin/ModuleCrudController.php) :

public function configureAssets(Assets $assets): Assets
    {
        $assets->addJsFile('assets/js/confirm-modal.js');

        return parent::configureAssets($assets);
    }

layout.html.twig (templates/bundles/EasyAdminBundle/layout.html.twig) :

{% extends '@!EasyAdmin/layout.html.twig' %}

{%  block content_footer_wrapper %}
    <div id="modal-confirm" class="modal fade" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <h4>Êtes-vous sûr ?</h4>
                    <p>Parce que ça va faire des trucs de fifou</p>
                </div>
                <div class="modal-footer">
                    <button type="button" data-bs-dismiss="modal" class="btn btn-secondary">
                        <span class="btn-label">{{ 'action.cancel'|trans([], 'EasyAdminBundle') }}</span>
                    </button>

                    <button type="button" data-bs-dismiss="modal" class="btn btn-success" id="modal-confirm-button">
                        <span class="btn-label">{{ 'action.confirm'|trans([], 'EasyAdminBundle') }}</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

confirm-modal.js (public/assets/js/confirm-modal.js) :

document.addEventListener("DOMContentLoaded",(
    function() {
        document.querySelectorAll(".confirm-action").forEach((function(e){
            e.addEventListener("click",(function(t){
                t.preventDefault();
                document.querySelector("#modal-confirm-button").addEventListener("click",(function(){
                    location.replace(e.getAttribute("href"));
                }));
            }));
        }));
    }
));

How do I use a regular expression from a string variable

In my current project, I have a CMS that is supplying all the data. One field of that CMS is for regular expressions, which allows me to enter my own specific expressions to check in the front end. My problem is that when I pull the regular expression it is coming through the escaped characters, and I can not seem to find a way to get around this.

The expression that I am using is /^d+$/. As I mentioned this is stored inside my CMS and I am attempting to use it in the following code:

            const re = /^d+$/;
            const rea = new RegExp(this.question.QuestionExpression);
            console.log(re);
            console.log(rea);
            console.log(this.answer)
            console.log(re.test(this.answer));
            console.log(rea.test(this.answer));
            console.log(this.answer.toString().match(this.question.QuestionExpression))

this.question.QuestionExpression is the Regular expression that is coming in from the CMS. The problem is not getting it, but how to interperet once I have it. const re is currently just being used as a test and has no real bearing on the final outcome.

The outcome from the above code is as follows:

/^d+$/
//^d+$//
13 
true 
false 
null

As you can see in the second line, it is adding escape characters which are causing it to fail on the 5th line. I am sure that I am missing something simple, but any advice would be greatly appreciated.

How to add attributes to a function called on an event?

I don’t know if the question is properly clear, but basically I’m adding an event and calling a function with that event, but I need to define some attributes for this function, is there any way similar to this:

var prop = 'hello'
        
function event(){
  console.log(this.prop) //hello
}

event.addAtribute = prop

window.addEventListener('click', event);

Dynamic content being vertically cut off

I’ve been using jsPdf to generate a pdf with dynamic content. What I do is go through all the forms I have and print the answers and questions.
Unfortunately when the content does not vertically fit the page it gets cut off instead of continuing in the next page.
How should I fix this?

“The DevTools has been shut out. It will automatically reconnect to DevTool once you reload the page.”

I’m working on a very simple tool for a company, it’s an aide to help visualize rail cuts.
I use a simple HTML page to build a display and then use JS to perform the simulated cuts and visualize them.

I have the file shared with some people via a shared drive. People in the US seem to be able to use the file without issue.

Someone in Europe tried to use the file and was able to open the file, but nothing happens upon trying to run the page’s script, and when f12 is pressed, they receive the message in the title (their system is in Japanese locale I believe, so it is roughly translated).

They do not have this problem if they save the file locally and run it from there, only when using it from the shared folder.

Running the file content through https://validator.w3.org/ yields no problems or errors.
It works for me and most others I have asked to try the tool.

Let me know if additional info is needed. I’d like to try avoid sharing code if possible because the company will get mad if I share the proprietary code I made but I can if I need to.

problems stopping audio recording API MediaRecorder

I have an application that uses MediaRecorder to record the audio of the calls, but it has some recordings that get stuck and are repeated for other calls, or it simply cuts the audio in half.

The start recording function:

function gravacaoAudio() {
console.log(“Gravação de Audio Iniciada”);

mediaOptions = {
    tag: 'audio',
    tipo: 'audio/mpeg',
    ext: '.mp3',
    opcao: { audio: true }
};

navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; 
if (navigator.getMedia) {
    navigator.getMedia({ audio: true, video: false }, function (stream) {
        if (navigator.userAgent.toLowerCase().search("edge") === -1 || navigator.userAgent.toLowerCase().search("msie") === -1) {
            recorder = new MediaRecorder(stream);
            recorder.ondataavailable = e => {
                partes.push(e.data);
                if (recorder.state === 'inactive') {
                    //Finalizo o atendimento

                    let idSenha = $('#hdnIdSenha').val();

                    if (idSenha != "") {
                        FinalizarAtendimento(servicosSelecionados, strChaveControle, strChaveControleComentario);
                    } else {
                        $("#chamarSenha").prop('disabled', false);

                        clearInterval(intervaloRelogioAoVivo);
                        clearInterval(intervaloCancelarAoVivo);
                        audioAoVivo('AGUARDANDO INÍCIO DE UM NOVO ATENDIMENTO...');
                    }
                    
                }
            };
        } else {

            audioAoVivoRemover('GRAVAÇÃO INDISPONÍVEL - PROBLEMA COM O NAVEGADOR');
        }
    }, function () {
        audioAoVivoRemover('GRAVAÇÃO INDISPONÍVEL - CALLBACK AUDIO');
    });
}
else {
    audioAoVivoRemover('GRAVAÇÃO INDISPONÍVEL - USE MEDIA');
}

}

And the stop recording function:

function StopGravacao() {

if (typeof recorder === "undefined") {
    //Finalizo o atendimento caso não exista gravacao de audio

    bootbox.alert("Não é possível finalizar o atendimento até que a gravação de áudio fique disponível, favor verifiquei o dispositivo de áudio!");

    //FinalizarAtendimento(servicosSelecionados, strChaveControle, strChaveControleComentario);
} else {
   
    screenStream.getTracks().forEach((track) =>
        screenStream.getTracks().forEach((track) =>
            voiceStream.getAudioTracks().forEach((audio) => audio.stop());
            if (recorder) {
                recorder.stop();
                $('.time').hide(); 
            }
            recorder = null;
        })
    );
}    

}