Object Creation for Multiple API Calls

Can an object be created with the help of which multiple API calls can be made? For example

  • I have two APIs to call, namely:-
export const getCropDetails = (cropDetails, token) => API.get(`/crop?name=${cropDetails}`, {
    headers: { "Content-Type": "application/json", "authorization": localStorage.getItem("token") }
});
export const getCropDetails = (cropDetails, token) => API.get(`/crop/details?name=${cropDetails}`, {
    headers: { "Content-Type": "application/json", "authorization": localStorage.getItem("token") }
});
  • Here I’m calling crops in the first and crop/details in the second.
  • I want to know if a class can be written, such that I can access them anywhere, rather than calling them multiple times every time.

ReactJS flush style updates of a div

I am attempting to write a self-centering self-sizing content editable div for a personal project. The text is centered and the width is set to 100% of the parent container, so I’m only concerned about height.

I have a function that changes the font size based on height differences between the child and parent containers. The next step is to check the difference with the applied changes and adjust if needed. Recalculation of the child height returns previous results as if the font re-sizing has not yet happened.

If the function is exited the font re-sizing happens, but I need to get the recalculation done without re-exiting. Any way to force flush the changes through?

I calculate child height through event.currentTarget.childNodes[i].offsetHeight (looping through text lines), and change the font size through event.currentTarget.style.fontSize =  (fontState + 'px');

Tried searching through the net, node documentation, and react documentation, but didn’t end up finding anything that would help.

Reasons for extremely high resource usage from websocket reconnection code?

I wrote what I thought was a relatively simple websocket app for a home project, and it mostly works, but if I leave the page idle for too long (a few days, multiple sleep/wake cycles of the computer) it starts to consume 100% CPU and large amounts of memory (I’ve seen as much as 11GB). Is there something I’m doing obviously wrong, or how should I go about debugging this?

<html>
<head>
    <title>Websocket Test</title>
    <script>
        var SOCKET = null;
        function startSocket() {
            SOCKET = new WebSocket('wss://[REDACTED]');
            SOCKET.addEventListener('open', function(event) {
                document.getElementById('disconnected-overlay').style.display = 'none';
            });
            SOCKET.addEventListener('close', function(event) {
                console.log("websocket closed: " + event.code + " (" + event.reason + ")");
                document.getElementById('disconnected-overlay').style.display = 'block';
                setTimeout(startSocket, 5000);
            });
            SOCKET.addEventListener('error', function(event) {
                console.log("websocket error: " + event);
                document.getElementById('disconnected-overlay').style.display = 'block';
                setTimeout(startSocket, 5000);
            });
        }
        function mainSetup() {
            startSocket();
        }
        setInterval(function() {
            console.log("4 minutes");
            if (SOCKET.readyState === WebSocket.OPEN){
                SOCKET.send(JSON.stringify({
                    "user_name": "debugging",
                    "change": { "AddMinutes": 0 },
                }));
            } else {
                console.log("socket was not open");
            }
        }, 240000);
    </script>
</head>
<body onload="mainSetup()">
    <div id="disconnected-overlay">Disconnected</div>
</body>
</html>

I’m currently using Firefox 111.0.1. I haven’t tested it on chrome/ium yet but I might try that soon. My best guess is the timeouts or callbacks from the setInterval are somehow accumulating while the page is idle and then all firing all at once, but I couldn’t find any documentation of that as expected behavior.

Object has been destroyed at win.webContents.send – Electron/node-pty

I am trying to create a terminal in my Electron app (similar to the one in vscode).
When I try to send the data that is created when the terminal (with win.webContents.send() an error occurs)

How can I send the data back to the renderer without this error occurring?
I am not sure what to do as I don’t have much experience in node-pty/electron.

Any help is appreciated. Thank you!

Error:

error

Main process:

const { app, BrowserWindow, ipcMain } = require('electron')
const path = require("path")
require('@electron/remote/main').initialize()


const createMainWindow = () => {
    const win = new BrowserWindow({
        width: 1920,
        height: 1080,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
            devTools: true
        },
        resizable: true,
        frame: false,
        devTools: true,
        contextIsolation: false,
        enableRemoteModule: true,
        //icon: path.join(__dirname + '/relico.ico'),
    })

    win.loadFile('./page-app/index.html')
    require('@electron/remote/main').enable(win.webContents)
}

const createLoaderWindow = () => {
    const win = new BrowserWindow({
        width: 300,
        height: 400,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
            devTools: true
        },
        resizable: false,
        frame: false,
        devTools: true,
        contextIsolation: false,
        enableRemoteModule: true,
        //icon: path.join(__dirname + '/relico.ico'),
    })

    win.loadFile('./page-app/loader.html')

    const pty = require("node-pty");
    const os = require("os");
    var shell = os.platform() === "win32" ? "powershell.exe" : "bash";

    var ptyProcess = pty.spawn(shell, [], {
        name: "xterm-color",
        cols: 80,
        rows: 30,
        cwd: process.env.HOME,
        env: process.env
    });

    ptyProcess.onData((data) => {
        process.stdout.write(data);
        win.webContents.send('terminal.incomingData', data);
    });


    ipcMain.on("terminal.keystroke", (event, key) => {
        console.log("KEY:", key)
        ptyProcess.write(key);
    });

    require('@electron/remote/main').enable(win.webContents)

}



app.whenReady().then(createLoaderWindow)

ipcMain.handle('openMain', async () => {
    createMainWindow();
    return true;
})

Render process:

const { Terminal } = require('xterm');
const { FitAddon } = require('xterm-addon-fit');
const { WebLinksAddon } = require('xterm-addon-web-links');
const os = require('os');

var term = new Terminal({
    cursorBlink: true,
    fontFamily: 'monospace',
    fontSize: 14,
    lineHeight: 1.4,
    scrollback: 1000,
});
term.open(document.getElementById('terminal'));

ipcRenderer.on("terminal.incomingData", (event, data) => {
    console.log("INCOMMING:")
    console.dir(data);
    term.write(data);
});

term.onData(e => {
    console.dir(e)
    ipcRenderer.send("terminal.keystroke", e);
});

How to handle EventStream POST requests with the webRequest API for browser extensions?

I’m trying to handle EventStream POST requests using the webRequest API in a browser extension. I’m not able to correctly process the event-stream chunks sent by the server. My goal is to intercept the response chunks and store them in my script. Nothing prints and no error is shown.

The code is part of my background.js script, everything up until console.log('Event-Stream response intercepted:', details); is working fine, so it is detecting the event-stream response:

browser.webRequest.onHeadersReceived.addListener((details) => {
  if (details.statusCode === 200 && details.type === 'xmlhttprequest') {
    for (let header of details.responseHeaders) {
      if (
        header.name.toLowerCase() === 'content-type'
        && header.value.toLowerCase().includes('event-stream')
      ) {
        console.log('Event-Stream response intercepted:', details);
        const filter = { urls: [details.url] };
        const streamId = details.requestId;

        // Filter response data
        const filterData = browser.webRequest.filterResponseData(streamId);
        const decoder = new TextDecoder('utf-8');
        let dataBuffer = '';

        filterData.ondata = (event) => {
          const chunk = decoder.decode(event.data, { stream: true });
          console.log('chunk', chunk);
          dataBuffer += chunk;

          // Process dataBuffer here or store it in eventStreamData for later use
          eventStreamData.set(streamId, dataBuffer);

          // Pass the chunk through without modifying it
          filterData.write(event.data);
        };

        filterData.onstop = () => {
          filterData.disconnect();
        };

        break;
      }
    }
  }
},
  { urls: ['*://*.example.com/*'] },
  ['responseHeaders']
);

The console.log('chunk', chunk); statement is not printing anything, so it seems like the stream is not being handled correctly. I’m not even sure that filterResponseData is the correct approach here. What am I doing wrong, and how can I properly handle the event-stream chunks with the webRequest API in a browser extension?

vimeo controls hide/show when custom fixed button clicking without autoplay

i have problem that i try to make popup inside swiper slide and vimeo players in tab.

it has 4 content boxes each tab inside.

first of all i want to solve this another content when i click the buttons(next or prev) going to change content and vimeo/slide too.

and changed another vimeo player will be initial start point and hide controls. it can be only customed buttons appear. when it come back(push the prev btn), it also initiated before i visited and click the button. the vimeo controls showing.

how can i write the code? or any vimeo handling method, event something? i have not clearly understand vimeo docs even i try do my best. because im foreigner actuallyTT

please help. i just try src attr change it work apart only(not whole mechanism) here is my code that i tried.

thank you

    const playBtn = $('#btn-play');

    const selectPlayers = ['212690002', '193832453', '18237484', '304719209', '108980280'];
    
    const iframe = $('iframe');
    const player = new Vimeo.Player(iframe);

    player.on('play', function() {
      console.log('played the video!');
    });

    let selPnum = 0;
    let selFrameUrl = iframe.attr('src');
    
    $('.desc_pagination').on('click', function(e) {
      playBtn.fadeIn(200);
      selPnum = $(this).hasClass('next') ? (selPnum + 1) % selectPlayers.length : (selPnum + selectPlayers.length - 1) % selectPlayers.length;
      vimeoRender();
    });
    
    playBtn.on('click', function(e) {
      console.log('1. Play setting start');
      e.stopImmediatePropagation();
      
      let useCtr = selFrameUrl.replace(/(controls=0)/g, function(vl){
        switch(vl){ case "controls=0": return "controls=1"; }
      });

      iframe.attr('src', selFrameUrl);
      
      iframe.on('load', ()=> {
        playBtn.fadeOut(200);
        setTimeout(()=> {
          player.play();
        }, 500)
      });

      
    });

    function vimeoRender() {
      let vurl = selFrameUrl.match(/player.vimeo.com/video/?([0-9]+)/i);
      selFrameUrl = selFrameUrl.replace(vurl[1], selectPlayers[selPnum]);
      iframe.attr('src', selFrameUrl);
    }

html :

<!-- inner video -->
<div class="video">
    <iframe src="https://player.vimeo.com/video/212690002?rel=0&title=0&showinfo=0&byline=0&controls=0&portrait=0&autopause=1&" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen allow="autoplay"></iframe>
    <button id="btn-play"><img src="images/main/video_play.png" alt="play"></button>
</div>
<!-- //inner video -->

try research vimeo docs

https://github.com/vimeo/player.js#embed-options
https://developer.vimeo.com/api/guides/start

and find googling

C# WebView2 – Localstorage-Request throws error

I’m recently working with the WebView2 in C# where I’m accessing to an API through an iframe.

Basically when the WebView2 gets initialized i call the method “ExecuteScriptAsync” where an HTML-Code gets executed which creates an iframe inside this html-code an then calls the api and shows me a website.

The problem is, when i call the API the iframe tries to get some information from the localstorage to initialize the website from the API and runs against an error.

Error trying to access the localStorage

i also tried to set the localStorage inside the iframe but this doesn’t work – i tried a lot of things but it won’t work -.-

I’m at the end of my knowledge, do you guys have an idea or a hint how to fix this?

Please say it if you need more information – i’ll add it.

Thank you guys!

Displaying Null or Undefined in React and JavaScript

I wanted to display the undefined or null values as italicize. If its empty string then output as is. If it has a value then output as is.

The problem right now is that its outputting as [Object Object] for null or undefined.

Codesandbox: CODESANDBOX

const columns: GridColDef[] = [
  { field: "id", hide: true },
  {
    field: "col1",
    headerName: "Column 1",
    width: 150,
    renderCell({ value }) {
      return `${
        value === null || value === undefined ? (
          <div style={{ fontStyle: "italic" }}>null</div>
        ) : (
          String(value)
        )
      }`;
    }
  },
  {
    field: "col2",
    headerName: "Column 2",
    width: 150,
    renderCell({ value }) {
      return `${
        value === null || value === undefined ? (
          <div style={{ fontStyle: "italic" }}>null</div>
        ) : (
          String(value)
        )
      }`;
    }
  }
];

How to overwrite values in array inside object

there.
I am recently learning JS and I get into the trouble, rn.
I use this method to overwrite values:

const person1 = {name: 'Jack', age: 10, job: 'developer'}
const person2 = {name: 'Su', age: 20}
const person3 = {name: 'Jin', job: 'singer'}
const result = {...person1, ...person2, ...person3} // {name: 'Jin', age: 20, job: 'singer'}

However, what if there is another object(array) inside object?
For instance:

const person1 = {name: 'Jack', age: 10, job: 'developer', hobbies: [{a:'baseball'}, {b:'basketball'}]}
const person2 = {name: 'Su', age: 20}
const person3 = {name: 'Jin', job: 'singer', hobbies: [a:'sing']}
const result = {...person1, ...person2, ...person3} // {name: 'Jin', age: 20, job: 'singer', hobbies: [a:'sing']}

I would like to keep the original values of hobbies and overwrite only one of them.
It looks like I have to use spread operator like I have used before, but I have no idea how and where to use it.
Is there any way or better approach to solve this issue?

Reload Last Carousel Image On Click

Can someone help me create a single script (vanilla or jquery) so that whenever I click on an image, the next time I refresh my browser the carousel loads that clicked image?

This is what I have so far:

When I click on an image in my carousel, this jquery script alerts me the index number of that slide:

    $('#myCarousel').on('click', '.mySlides', function () {
        alert( $(this).index('.mySlides')+1 );
    });
}); 
//Alert! 7 (ie. Current image slide is 7/10, etc)```

I have a separte vanilla javascript when I refresh my browser, the carousel loads a specific image but I have to manually insert the index number:

```window.addEventListener("load", (event) => {
  currentSlide(7); 
});```

I've reached my limit on how to make this work as a single script. Appreciate all the help :)

React native make smooth scrolling animation with collapsing header

I am pretty new to react native. I am trying to make a collapsable header when I scroll upwards with a scrollview. Something like this:

https://medium.com/swlh/making-a-collapsible-sticky-header-animations-with-react-native-6ad7763875c3

I got it wokring but I am not really it’s not exactly what I want. So this only works when the scrollview is long enough so you can actually scroll and let it collapse.

So I was trying to make it work so when the scrollview is not long enough it will collapse no matter what. I only got it working by adding a padding on the bottom of the scrollview. What I don’t like as well.

And another thing that I want, but do not know how to perform. Is when I start scrolling that the scrollview go automatically to the top of the screen, instead of it staying where I dragged it to.

This is what I have atm:

const [listHeight, setListHeight] = useState(null)

    const insets = useSafeAreaInsets();

    const HEADER_HEIGHT = 200;
    const scrollOffsetY = useRef(new Animated.Value(0)).current;

    const headerHeight = scrollOffsetY.interpolate({
        inputRange: [0, HEADER_HEIGHT],
        outputRange: [HEADER_HEIGHT + insets.top, insets.top + 40 ],
        extrapolateRight: 'clamp'
    });

    return (
        <SafeAreaProvider style={{backgroundColor: colors.bgColor, flex: 1 }} >

            <SafeAreaView style={globalStyles.droidSafeArea} forceInset={{ top: 'always' }}>
                <Animated.ScrollView
                    contentInsetAdjustmentBehavior="automatic"
                    stickyHeaderIndices={[1]}
                    bounces={false}
                    contentContainerStyle={{
                        paddingBottom: listHeight / 2.3 - insets.top,
                    }}
                    scrollEventThrottle={16}
                    onScroll={ Animated.event(
                        [
                            {
                                nativeEvent:
                                    {
                                        contentOffset: { y: scrollOffsetY }
                                    }
                            }
                        ], {useNativeDriver: false})
                    }
                    onLayout={(evt) => {
                        const listH = evt.nativeEvent.layout.height;
                        setListHeight(listH)
                    }}
                >

                    <Animated.View
                        style={{
                            justifyContent: "center",
                            alignItems: "center",
                            height: headerHeight,
                        }}
                    >
                        <Animated.Text
                            style={[
                                {
                                    color: "white"
                                }
                            ]}
                        >My progression</Animated.Text>
                    </Animated.View>

                    <Animated.View
                        style={{
                            justifyContent: "center",
                            backgroundColor: colors.bgColor,
                            padding: 10,
                            height: 40,
                        }}
                    >
                        <Animated.Text
                            style={[
                                {
                                    color: "white"
                                }
                            ]}
                        >My progression</Animated.Text>
                    </Animated.View>

                    <View
                        style={{padding: 10}}
                    >
                        <View
                            style={[
                                {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                            ]}
                        >

                        </View>

                        <View
                            style={[
                                {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                            ]}
                        >

                        </View>

                        <View
                            style={[
                                {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                            ]}
                        >

                        </View>

                        <View
                            style={[
                                {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                            ]}
                        >

                        </View>

                        <View
                            style={[
                                {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                            ]}
                        >

                        </View>

                        <View
                            style={[
                                {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                            ]}
                        >

                        </View>
                        <View
                            style={[
                                {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                            ]}
                        >

                        </View><View
                        style={[
                            {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                        ]}
                    >

                    </View><View
                        style={[
                            {height: 80, backgroundColor: colors.secondary2, borderRadius: 8, marginBottom: 10}
                        ]}
                    >

                    </View>



                    </View>
                </Animated.ScrollView>
            </SafeAreaView>
        </SafeAreaProvider>

Could you guys please help me?

Thanks in advance

cannot find module ‘next/router’ or its corresponding type declarations

Currently having some problems with my NextJS app.

I get the error below. Which is really weird, because my code runs perfectly with no errors.

import { useRouter } from 'next/router';
// Cannot find module 'next/router' or its corresponding type declarations.

However, I get the error above in my IDE, this error is stopping my turbo build and yarn build commands to run, causing me to be unable to be able to push to production.

I have restarted my ts server, uninstalled next, updated to latest version and ran yarn to install everything again.

I’ve made an example repository on GitHub. https://github.com/MonkeeMan1/test

This is happening for all my next imports.
Cannot find module 'next/router' or its corresponding type declarations.ts(2307)
Cannot find module 'next/link' or its corresponding type declarations.ts(2307)
Cannot find module 'next/image' or its corresponding type declarations.ts(2307)

Package.json
https://hatebin.com/ylujtdhtht

I have tried using moduleResolution node, as well as node16

node results in my local package cachetesting to not be found, so it is unable to be imported. And node16 results in nextjs import errors.

Ag-grid pivot avoid column aggregation

I have an Ag-grid pivot table with row groups and column defs.
Is there a way to hide the “Total” column while still having an expandable pivot column groups and the same aggFunc for the row groups?

Example:
The current state
The current state

What I want
What I want

Code:

const gridOptions = {
  columnDefs: [
    { field: 'country', rowGroup: true, enableRowGroup: true },
    { field: 'athlete', rowGroup: true, enableRowGroup: true },
    { field: 'sport', pivot: true, enablePivot: true },
    { field: 'year', pivot: true, enablePivot: true },
    { field: 'gold', aggFunc: 'sum' },
    { field: 'silver', aggFunc: 'sum' },
    { field: 'bronze', aggFunc: 'sum' },
  ],
  defaultColDef: {
    maxWidth: 140,
    filter: true,
    resizable: true,
  },
  autoGroupColumnDef: {
    minWidth: 180,
  },
  pivotMode: true,
  pivotColumnGroupTotals: 'before',
};

Thanks!

jQuery slider is not moving divs

I have tried looking at other stacks but couldn’t find any help. Basically my slider isn’t moving and the divs are stacked on one another. I am using bxslider My code:

console.log("slider code loaded")
 jQuery('.slider').bxSlider({
  autoControls: true,
  auto: true,
  pager: true,
  slideWidth: 600,
  mode: 'fade',
  captions: true,
  speed: 1000
});

(function($) {
  $.fn.slider = function(options) {
    // default settings
    var settings = $.extend({
      speed: 1000,
      pause: 3000
    }, options);
    var slider = this;
    var slides = slider.find('.slide');
    var currentSlide = 0;
    // show first slide
    jQuery(slides[currentSlide]).fadeIn(settings.speed);
    // loop through slides
    setInterval(function() {
      // hide current slide
      jQuery(slides[currentSlide]).fadeOut(settings.speed);
      // move to next slide
      currentSlide++;
      if (currentSlide >= slides.length) {
        currentSlide = 0;
      }
      // show next slide
      jQuery(slides[currentSlide]).fadeIn(settings.speed);
    }, settings.pause);
    return this;
  };
}(jQuery));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/bxslider/4.2.12/jquery.bxslider.css">
<script "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script "text/javascript" src="https://cdn.jsdelivr.net/bxslider/4.2.12/jquery.bxslider.min.js"></script>
<!-- Load jQuery -->
<script src="js/jquery.min.js"></script>

<!-- Load slider script with jQuery as dependency -->
<script src="js/jquery-slider.js"></script>
<!-- Load CSS file -->
<link rel="stylesheet" href="css/jquery-slider.css">

<div class="slider">
    <h2>Slide One</h2>
    <h2>Slide Two</h2>
    <h2>Slide Three</h2>
</div>

I can see that “slider code loaded” is logged and no errors in console. But nothing seems to be happening. Can anyone please help me out? Thanks in advance.