How to handle errors coming from nextjs’s router.refresh?

I’m having a page that getting refreshed every few seconds using router refresh

    const router = useRouter()

    ...

    useEffect(() => {
        interval = setInterval(() => {
            router.refresh()
        }, REFRESH_RATE_MIL)
        return () => {
            clearInterval(interval)
        }
    }, []);

The problem is, when the machine is entering to hydration (sleep mode or closing the screen and wait a few minutes) The app crashes with net::ERR_NETWORK_IO_SUSPENDED, causing the whole application to crash.

I’m using Mac Ventura 13 and Chrome Version 127.0.6533.72 (arm64)

I tried few things to solve it:

  1. Add user idle detection to clear the interval – that doesn’t solve the case when you close the lid (screen) of the machine.
  2. catch the router refresh using try catch clauses
  3. read the nextjs docs and the router.refresh (” Refresh the current page. refresh(): void;”) to try to figure out if there is any option/callback I can use to catch it.
  4. Searched MDN and googled if there is anyway to detect the ERR_NETWORK_IO_SUSPENDED ( and then prevent the router.refresh trigger)
  5. searched next issues for issues related to ‘router.refresh error handling’ or ERR_NETWORK_IO_SUSPENDED
  6. looked stackoverflow for related questions. Find this old one

** I want to use the router refresh because of the caching ability and the fact that it preserves the component’s state

Any ideas of how to address this?

heroku.cmd”‘ is not recognized as an internal or external command, operable program or batch file

Not able to use Heroku CLI in VS code. get error “heroku.cmd”‘ is not recognized as an internal or external command,
operable program or batch file.”

Many people say to uninstall and install again, then restart and this does not work.
Also, some say to add to path and this has not worked.

I have searched for help in Heroku and Stackoverflow and the above solutions were suggested and have not worked.

Any suggestions that anyone would have will be greatly appreciated.

thanks

Do not see help in he

“Failed to load resource: net::ERR_FILE_NOT_FOUND” Electron

Cannot load

enter image description here

Resource of CalHeatmap not found when testing app in Electron. I check on my vscode that clicked new CalHeatmap(); will jump into the source file, so it should be work, but when try to npm start the resource not found.

Notes:

  • In load.js focus on imports and focus on line <script type="module" src="./load.js"></script> in index.html. Let me know if you still need info.
  • I already manage to get work of cal-heatmap in VITE then I try to make into Electron. In VITE project all it’s fine, but in Electron project it’s not.
  • If you need more information, let me know in the comment.

load.js

import CalHeatmap from './node_modules/cal-heatmap';
import './node_modules/cal-heatmap/cal-heatmap.css';

// Instantiate CalHeatmap
const cal = new CalHeatmap();

const _data = {
    data: {
        source: 'https://raw.githubusercontent.com/vega/vega/main/docs/data/seattle-weather.csv',
        type: 'csv',
        x: 'date',
        y: d => +d['temp_max'],
        groupY: 'max',
    },
    date: { start: new Date('2012-01-01') },
    range: 12,
    scale: {
        color: {
            type: 'threshold',
            range: ['#14432a', '#166b34', '#37a446', '#4dd05a'],
            domain: [10, 20, 30],
        },
    },
    domain: {
        type: 'month',
        gutter: 4,
        label: { text: 'MMM', textAlign: 'start', position: 'top' },
    },
    subDomain: { type: 'ghDay', radius: 2, width: 11, height: 11, gutter: 4 },
}


cal.paint(_data);

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>Hello World!</h1>
    <p>
        We are using Node.js <span id="node-version"></span>,
        Chromium <span id="chrome-version"></span>,
        and Electron <span id="electron-version"></span>.
    </p>
    <div id="cal-heatmap"></div>
    <script type="module" src="./load.js"></script>
</body>
</html>

JavaScript loop running on console but not on code

I’m trying to make a a JS forEach loop that is supposed to run after the DOM is fully loaded, but for some reason it won’t run on code but when I put the same loop on console it runs fine.

window.onload = (event) => {

    var checkboxes = document.getElementsByName("plates")
    var labelPlate = document.getElementsByName("labelPlate")

    checkboxes.forEach((i, index) => {
        if (i.checked) {

            labelPlate[index].classList.add("active")
        } else {
            labelPlate[index].classList.remove("active")
        }
    })
};

Loop is supposed to run.

asp.net with vue js FsLightbox lybrary Access to XMLHttpRequest origin has been blocked by CORS policy

asp.net with vue js FsLightbox lybrary Access to XMLHttpRequest at ‘https://localhost:44347/CarImages/3e0da2fa7fd0417ea2e2f4678229e264Logo.png’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. error

when use FsLightbox library show this error , im use this images path in another slider its run good
and im use another images from internet to FsLightbox also run good
this problem just appear when use my images paths with FsLightbox !!??

// this is policy code from program.cs 
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            //you can configure your custom policy
            builder.AllowAnyOrigin()
                                .AllowAnyHeader()
                                .AllowAnyMethod();
        });
});
var app = builder.Build();
// Apply CORS policy
app.UseCors();

/////////////////////

// this in vue js FsLightbox like documntation
<FsLightbox :toggler="toggler" :sources="vehicleImages" />

Update columns of DataTable after having the data from server

I’m new at DataTables js, I need a solution for my problem. I have a Django app where I use DataTables with server-side processing, the table template is dynamic for all the models I have, I just pass the columns (a list of dicts with data, name and title) within the context of the template, pretty straightforward…

def my_page_view(request):
    columns = generate_datatables_columns("MyModel")

    return render(
        request,
        "my_page.html",
        {"columns": columns}
    )
<script>
    $(document).ready(function() {
        var columns = [];
        {% for col in columns %}
            var jsObject = {
                {% for key, value in col.items %}
                    "{{ key }}": "{{ value }}",
                {% endfor %}
            };
            columns.push(jsObject);
        {% endfor %}

        var table = $('#my-table').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "/my/url",
                "type": "GET",
            },
            "columns": columns,
        });
    });
</script>

<table id="my-table" class="display" width="100%">
    <thead>
        <tr>
            {% for column in columns %}
                <th id="dt_col_{{column.data}}">{{ column.name }}</th>
            {% endfor %}
        </tr>
    </thead>
</table>

After that, I needed to make some changes on the columns, but depending on the data received, meaning I should be able to update my columns inside the DataTable definition after having the data. To make the idea clearer, the following code represents one of the attempts I tried, using ajax.dataSrc prop:

var table = $('#my-table').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "/my/url",
        "type": "GET",
        "dataSrc": function (json) {
            var data = json.data;
            var newColumns = columns;

            // make changes on data and newColumns variables with some conditions...
            
            // here should update the datatable columns with the value of newColumns.

            return data;
        }
    },
    "columns": columns,
});

With this method I couldn’t find a way to update the columns, I tried also other ways like using drawCallback, or custom ajax function, but I always end up with a dead-end.

I will be really grateful if someone helped me with that.

Shopify App Proxy – Ajax HTTP POST Request Returns 400 Bad Request:

I’m working on a Shopify app that includes an AJAX POST request to a proxy app URL. The request works fine locally and on ngrok, but when deployed to Shopify, I receive a 400 Bad Request error.

I made several posts on Shopify’s Community Forums, messaged Shopify developers, surfed Youtube, and checked the documentation many times – unfortunately I have yet to resolve this problem.

To provide more details, I am leveraging a .NET Razorpage application, where the frontend displayed by my proxy app is written in the razor view, and the handler methods my ajax calls hit are in the code-behind file. I configured my proxy url path as apps/member. The following ajax call is meant to take submitted form data by the user and pass it to my backend file. The ajax call that works locally and through ngrok’s url:

$.ajax({
    type: 'POST',
    url: '/apps/member?handler=MethodName',
    contentType: 'application/json',
    data: JSON.stringify(formData),
    headers: {
   
        'RequestVerificationToken': antiForgeryToken,
        'Content-Type': 'application/json'
        
    },
    dataType: 'json',
    beforeSend: function (jqXHR, settings) {
        console.log('Request URL:', settings.url);
        console.log('Request Type:', settings.type);
 
    },
    xhrFields: {
        withCredentials: true
    },
    success: function (response) {
        if (response.success) {
            $('#UserFeedbackMessage').text(response.message).css('color', 'green').show();
        } else {
            $('#UserFeedbackMessage').text(response.message).css('color', 'red').show();
        }
    },
    error: function (xhr, status, error) {
        console.error("Error updating collector info:", error);
        console.log("XHR:", xhr);
        console.log("Status:", status);
        console.log("Response Text:", xhr.responseText);
        $('#UserFeedbackMessage').text("An error occurred while updating your profile.").css('color', 'red').show();
    },
    complete: function (jqXHR, status) {
        console.log('Complete Response Headers:', jqXHR.getAllResponseHeaders());
    }
});

What makes this issue weirder is that this approach was working a year ago, but I know how frequently Shopify updates. I want to know the following:

  • Are only ajax GET requests allowed for proxy urls?

  • For moving data from the client side to an external api, what is the most common approach?

I tried to leverage a theme-app-extension by placing the ajax call in there and triggering it with a button to see if it made a difference – negative.

I tried to leverage the “method” and “post” attributes of the form tag:

<form id="updateCollectorForm" method="post" action="/apps/member-area?handler=UpdateCollectorInfo">

this also didn’t work (believe it or not, this was working a little over a year ago on Shopify…)

How i can insert data in ckeditor textarea

i am trying to edit a textarea whis is ckeditor but iam facing issue if some one kown please tell me.

HTML CODE

  <div class="col-md-12">
                <a class="btn btn-primary pull-right" id="nextdiv">
                    <i class="fa fa-plus"></i>
                </a>
                {!! Form::label('content', __('lang_v1.content') . ':*') !!}
                <div id="editor-container">
                    <div class="printableArea ck-editor__editable_inline">
                        {!! Form::textarea('content[]', null, [
                            'class' => 'form-control editor updateEditor',
                            'placeholder' => __('lang_v1.content'),
                            'id' => 'editor',
                        ]) !!}
                    </div>
                </div>
                <div id="container"></div>
            </div>

js code
$(“.template”).on(‘change’, function() {

$.ajax({
url: ‘/get/template/data/’ + templateId,
type: ‘GET’,
success: function(response) {
console.log(response.content)
CKEDITOR.instances[‘editor’].setData(response.content);
}
)}
}

IT GIVE THIS ERROR
TypeError: Cannot read properties of undefined (reading ‘editor’)

WHERE IS ISSUE I AM DOING

Problems on flatlist scroll in iOS

I have a Flatlist, simple flatlist. The scroll in iOS only do if I use 3 fingers.
Each list on flatlist, is a touchableOpacity, the button can be a problem?
I need make the scroll with 1 finger;

   <FlatList
     data={options.options}
     keyExtractor={(item) => String((item as any).id)}
     showsHorizontalScrollIndicator={false}
     showsVerticalScrollIndicator={true}
     initialNumToRender={10}
     maxToRenderPerBatch={10}
     renderItem={ListItem}
   />

Item

function ListItem({ item }: { item: Item }) {
    return (
      <TouchableOpacity
        key={item.value}
        style={{
          height: 50,
          justifyContent: 'center',
          alignItems: 'center',
          borderBottomWidth: 1,
          borderColor: theme.palette.border,
        }}
        onPress={() => onItemSelected(item)}
      >
        <Orientation.Row
          style={{ justifyContent: 'center', gap: 8, width: 280 }}
        >
          {options.selected?.value === item.value && (
            <FontAwesome5 name="check" size={12} color={theme.palette.text} />
          )}
          <Typography.Default
            style={{
              fontSize: 18,
              fontFamily: theme.fonts.BOLD,
              textAlign: 'center',
            }}
          >
            {item.label}
          </Typography.Default>
        </Orientation.Row>
      </TouchableOpacity>
    );
  }

I need do the scroll in the list with 1 finger, like anywhere lists. But in iOS (all I tested), only make the scroll with 3 fingers. Wtf.

Vanilla html js css with some super power from parcel

I am working on a simple side project. The stuffs are very simple, I just need some simple html css and vanilla javascript. Everything is static so that I can simply use Cloudflare Page.

That said, I would like to have some super power from modern frontend tools that can compact the html, js, css and also perform tree shaking. Then I bring in parcel, daisyUI and tailwind.

There is one thing really missing. In the old php days, we can template the page by including other php files like including header.php and including footer.php.

The target is to reuse the template of the page, including the and sections. Web component could be an alternative but it cannot let me reuse all the stuffs in the and section.

Does anyone know any tools can achieve that? Thank you!

Playwright Post request giving Error: apiRequestContext.post: getaddrinfo ENOTFOUND intermitently

I am running into an issue where in Playwright I am getting this error every 15 or so requests
Error: apiRequestContext.post: getaddrinfo ENOTFOUND
for the URL I am using an https:// development server endpoint. The same exact request can pass and then fail, and when I debug the tests they are always passing. Here is a helper function where it is running the post that is throwing the error:

public static async postJSONX_Access(request: APIRequestContext, endpoint: string,body: object, xAccessToken: string | undefined ) : Promise<any> 
{
        const response = await request.post(endpoint, {
            data:body,
            headers: {
            'X-Access-Token' : xAccessToken!
            },
        });
        expect(response.ok());
        return await response.json();
    }

Full error log here:

Error: apiRequestContext.post: getaddrinfo ENOTFOUND d-api.company.com
Call log:

  • → POST d-api.company.com/post/data
  • user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.17 Safari/537.36
  • accept: /
  • accept-encoding: gzip,deflate,br
  • X-Access-Token: tokenGoesHere
  • content-type: application/json
  • content-length: 2

I am testing two APIs and only running into this issue on one of them. Any help would be appreciated, I tried the solution from this question API GET Request test using Playwright on adding

import dns from "dns"; dns.setDefaultResultOrder("ipv4first");

To my playwright.config.js folder and it didn’t work to resolve the issue.

I am expecting what happens most of the time where the POST request goes through and the response is returned. I have tried removing https:// from the baseURL, I have tried adding
import dns from "dns"; dns.setDefaultResultOrder("ipv4first");
To the config file, I have tried running ipconfig /flushdns. When I restart my computer it is working to pass all the tests but over time these failures start popping up.

Instantly set Embla Carousel slide index without animation

I’m building a gallery component in where clicking on an image opens a <dialog> containing an embla-carousel. The problem is that when I click on an image, the carousel always opens at index 1, regardless of which image was clicked. I tried to fix this by using emblaMainApi.scrollTo(selectedIdx.value) to get to the carousel’s position based on the clicked image index, but this causes an scrolling animation from slide 1 to the selected slide, which looks weird.

I want the selected image to appear instantly in the carousel without any scrolling animation.

I’m looking for a possible solution.

<template>
<div>
  <ItemModal ref="modalRef" :imgs="imgs" />
  <div v-for="(item, idx) in imgs" :key="item">
    <NuxtImg
    :src="`${item}`"
     :alt="`gallery image ${idx}`"
    @click="showImg(idx)"
    />
  </div>
</div>
</template>

// *script*

// gallery.vue
const imgs = [
  "/images/gallery/gallery-1.jpg",
  "/images/gallery/gallery-2.jpg",
  "/images/gallery/gallery-3.jpg",
];

const modalRef = ref(null);

const showImg = (index) => {
  if (modalRef.value) {
    modalRef.value.show(index);
  }
};

// modal.vue. Here I expose the 'show' method to the 'gallery' parent component so I can use it there
defineExpose({
  show: (index: number) => {
    selectedIdx.value = index;
    isOpen.value = true;
    dialog.value?.showModal(); // showModal() is a native `dialog`'s method
  },
});

Eliminate CORS in using inject.js script

I want to embed a chatbot in a website by pasting two lines of code.

For this, I have written a script.js that is hosted on

raw.githubusercontent.com/vikas70607/Botpress/main/Script.js

But this script is blocked by CORS as it is coming from an external source.
But others platform provides uses similar concept like


<script src="https://cdn.botpress.cloud/webchat/v1/inject.js"></script> 

and this works too.

Any help or Advice Regarding this.

I tried using only Vanilla JS, am I missing something? or should I be using node.

Print PDF file with highlighted texts using viewer.js

I am using viewer.js and trying to print pdf file with highlighted text in it.

I have tried to print pdf file by selecting background graphic, but it did not work. I have also used
-webkit-print-color-adjust: exact; in @media print but it also did not work.

Print Container

Note: I might be doing in wrong way. Suggesting me to solve in the right directions would be appreciable.