Leaflet map included in an html exported from Obsidian.md only shows up after page reload / refresh

My goal:
I exported some html notes from Obsidian.md (based on this: https://github.com/KosmosisDire/obsidian-webpage-export) and am now trying to include a fictional worldmap based on the leaflet.js script (not using the leaflet Plugin for Obsidian, since this didn’t work for me in the export).

My problem:
When first opening the page or navigating there from another note in the hierarchy, the map and UI are gone. Which means that I only see a completely empty frame in the size of the map. So I’m just guessing that the script isn’t loaded (including the Map UI overlay). The map only works fine after I reload the page, showing the typical leaflet zoom UI as well.

I’m testing everything locally with the help of VS Code and Five Server as local webserver. There are no errors in my code (I fixed some errors caused by the generated export from Obsidian). The same problem is visible when I upload it to my webspace or try it with different browsers.

Hoping that someone here can help me, since I’m pretty sure that others who would like to have such an interactive worldmap combined with an Obsidian based page as well might stumble on this problem as well and hopefully also find the solution for this here some day.

What i tried so far:
I looked on stackoverflow for similar questions and already tried solutions not only for leaflet but also for other problems with scripts not executing without a refresh/reload of the page. But nothing helped.

I included the script in a simpler html and played around with a link to another page and returning to the one with the map – it worked. So I guess it’s a problem with something the other scripts in the document do (there is some ajax and pixy included which I can’t remove since it’s needed for a graphview navigation which is part of Obsidian).

I searched on stackoverflow for solutions again.
I tried using cache, defer, preload and placing the link to the script and the script (and css) itself into different places in the html file and different folders.
I tried removing other scripts in the html file to see if it helps.

But all of this didn’t change the behaviour, only caused more errors and problems on the page (or with the leaflet UI).

So far, I haven’t found any solution that helped me. I don’t get any error message, so there is nothing I can post here unfortunately.

And yes, I am no programmer/web dev, so unfortunately I am currently not able to come up with any more elaborate solutions. I was just looking for a way to present my writing/content in a nice way.

This is my map script itself:

<script> 
// Using leaflet.js to pan and zoom a big image. 
           const map = L.map('image-map', {
             minZoom: 1,
             maxZoom: 4,
             center: [0, 0],
             zoom: 1,
             maxBoundsViscosity: 1,
             crs: L.CRS.Simple
           });
           var image= L.imageOverlay("I removed the name of my asset here, but using a webp which works", [[0,0],[240,330]]); //initial size at zoom 1 )
           image.addTo(map);
// tell leaflet that the map is exactly as big as the image
map.setMaxBounds(new L.LatLngBounds([0,0], [240,330]));  // prevent panning outside the image area.
    //Note the viscosity setting keeps the image from being dragged outside this 
</script>

Fillable Field format [closed]

How to identify fillable form field type, format and character limits using Javascript.

I want to extract fillable field properties like below.

Field Name: —–
Field Type:——
Field Format: Date, Phone number, Social security number etc.
Field Character limit

expressjs not handling get requests

I am making an expressjs api with Google oauth enabled. However I’ve got an issue. I’m using thunderclient to test my api and for some reason I get an error whenever I try and go a .get request.

const express = require("express");
const router = express.Router();
const passport = require("passport");
const {
  registerUser,
  loginUser,
  logoutUser,
  googleOauth2Callback,
} = require("../controllers/auth.controller");
const { validateLogin } = require("../validation/user.validation");

router.post("/register", registerUser);

router.post("/login", validateLogin, passport.authenticate("local"), loginUser);

router.post("/logout", logoutUser);

router.get("/google/failureRedirect", (req, res, next) => {
  console.log("failed login");
  res.status(400).json({ message: "Google authentication failed" });
});

module.exports = router;

Here is my route /api/v1/auth/. When I try and access /api/v1/auth/google/failureRedirect with thunderclient I get an error. If I change it to make it a post request then it works. If it helps any here is my app.js

const express = require("express");
const compression = require("compression");
const createSession = require("./config/session.config");
const configureMorgan = require("./config/morgan.config");
const initializeDotenv = require("./config/dotenv.config");
const xss = require("xss-clean");
const bodyParser = require("body-parser");
const helmet = require("helmet");
const configureCors = require("./config/cors.config");
const passport = require("passport");
require("./config/passport.config");

// Required routes
const errorRoute = require("./routes/error.route");
const authRoute = require("./routes/auth.route");

// Middleware
const { catchErrors } = require("./middleware/catchErrors");
const { controlHeaders } = require("./middleware/controlHeaders");

// Initialize app
const app = express();

// Protect headers
app.use(helmet());

// Use xss-clean middleware
app.use(xss());

// Initialize Dotenv
initializeDotenv();

// Compress res body to send JSON to client quicker
app.use(compression());

// Configure which domains can be access API
app.use(configureCors());

// Allows req.body and req.query params able to be accessed
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//----- log events in dev mode -----//
configureMorgan(app);

//-----session setup-----//
createSession(app);

//----middleware----//
app.use(controlHeaders);

//----passport setup-----//
app.use(passport.initialize());
app.use(passport.session());

//-----routes-----//
app.use("*", errorRoute);
app.use("/api/v1/auth", authRoute);

//-----middleware-----//
app.use(catchErrors);

module.exports = app;

Unable to get textcontent of an element using page.evaluate

I am updating firstname and trying to verify it . I am unable to see the updated firstname in DOM but it is visible in UI. Below is the code I am using

var updatedFirstName = await page.evaluate(() => document.querySelector('[data-placeholder = "First Name"]').textContent)

console.log('updated firstname is ' +updatedFirstName)

I am receiving empty in place of +updatedFirstName in console.

Getting CORS Error when calling BambooHR API

I’m trying to call the BambooHR API in my React (TS) project, but I keep getting CORS error from both localhost and server. I’m not sure why as this API is supposed to be public.
The API call works on Postman but it doesn’t on the client.

I followed their API docs: https://documentation.bamboohr.com/docs/getting-started
https://{API Key}:[email protected]/api/gateway.php/{subdomain}/v1/employees/directory

It’s very basic. How do I fix this?

How to hide a popover when clicking outside of it

In my web page, I have a popover that shows information from a remote URL, this way:

$('*[data-poload]').on('click', function(evt) {
    evt.preventDefault();
    var e=$(this);
    $.get(e.data('poload'), function(d) {
        var titulo = d.title + ' - ' + moment(d.sentWhen).format('DD-MM-YYYY HH:mm');
        var texto = d.text;
        e.popover({title: titulo, content: texto}).popover('show');
    });
});

This is the A tag:

<a href="#" tabindex="0" data-bs-placement="auto" data-poload="the_remote_link">

With that code, the popover is shown, but when clicking outside of it or in another popover, previous one is not hidden.

How can I do it?

How do I map one array at random with no duplicates and also include an item from a repeating array?

I have a JSON file with data in it that I’m trying to map out.

 const randomCategories = []

  for (let i = 0; i < 10; i++) {
    const randomIndex = Math.floor(Math.random() * categoryData.length)
    const randomCategory = categoryData[randomIndex]
    console.log(randomCategory)
    randomCategories.push(randomCategory)
  }

I only want 10 items from the categoryData array without any duplicates. I cannot get anything to work that removes duplicates or doesn’t include them to begin with.

There’s a second array as well:

  const colors = [
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(139,0,0)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(0,0,139)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(184,134,11)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(0,100,0)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(0,139,139)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(139,0,139)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(233,140,0)"
    }
  ]

Colors does not need to be randomized, it’s fine in the order it is in.

From there, I’m mapping out items from randomCategories into a grid of components for the data

 <div className="grid grid-rows-1 grid-flow-col w-[2360px] h-[233px] max-h-[233px] gap-x-3">
      {randomCategories.map((item) => (
        <CategoryCard key={item?.id} name={item?.name} image={item?.image} />
      ))}

    </div>

The idea is that I’ll generate an array of 10 random, unique items from categoryData and display those 10 items in 10 CategoryCards. Each CategoryCard should have a color from the colors array in it, in the same order. So if it’s red, green, blue, yellow, etc. once I reach the end of the colors array it repeats again; red, green, blue, yellow, etc. I’m not sure how to include the colors in the .map function or how I’d go about having that array repeat?

Attached picture is what I’m trying to accomplish:

This is what I'm going for

GSAP Parallax Two Divs

im trying to make a parallax effect the way while scrolling the logo change color, for exemple:
LOGO PARALLAX EFFECT

im trying to use GSAP, my initial idea was pin the divs, but they doesnt make the effect i want, i saw a way of making it with background-attachement: fixed, but that doesnt work for IOS, and because im using GSAP in my project i though it was possible to make the effect i want with it

this is my HTML

<section class="logo-parallax">
        <div class="background">
          <img class="logo" src="/media/svg/logo-azul.svg" alt="">
        </div>
        <div class="container">
          <img class="logo" src="/media/svg/logo-branco.svg" alt="">
        </div>
      </section>

this is my SCSS

.logo-parallax {
    .background,
    .container {
      max-width: initial;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;

      .logo {
        max-width: 850px;
      }
    }

    .background {
      background-color: $white; // white
    }
    .container {
      background-color: $mainColor; // blue
    }
  }

and this is my JS

// parallax
// Define GSAP animations
gsap.to(".logo-parallax .background", {
  scrollTrigger: {
    trigger: ".logo-parallax .background",
    start: "top top",
    end: "+=100%",
    pin: true,
    pinSpace: false,
    scrub: true, // Smooth animation
  },
});
gsap.to(".logo-parallax .container", {
  scrollTrigger: {
    trigger: ".logo-parallax .container",
    start: "top top",
    end: "bottom bottom",
    pin: true,
    pinSpace: false,
    scrub: true, // Smooth animation
  },
}); 

can someone help me?

why does the web socket give an error when connecting to the server?

I am trying to connect to a web socket on the server, to which the socket gives an error stating that it was failed to connect

rust code:

use axum::{extract::{ws::WebSocket, WebSocketUpgrade}, response::IntoResponse, routing::get, Router};
use tokio::net::TcpListener;
use tower_http::services::ServeDir;


#[tokio::main]
async fn main(){
  let listener = TcpListener::bind("localhost:3000").await.unwrap();
  axum::serve(listener, router()).await.unwrap();  
}

fn router() -> Router{
    Router::new()
        .route("/message_list", get(hello_world))
        .nest_service("/", ServeDir::new("static"))
}

async fn hello_world(ws: WebSocketUpgrade) -> impl IntoResponse{
    let _res =ws.on_upgrade(|ws| socet_handler(ws));
}

async fn socet_handler(mut ws: WebSocket){
    println!("IT READY!");
    let _res = 
    ws.send(axum::extract::ws::Message::Text('hi'.to_string()));
}

js code:

let socket = new WebSocket("ws://localhost:3000/message_list")

i try to change ‘ws’ to ‘wss’ on path but it doesnt help.
there is a constant error on the site: WebSocket connection to ‘ws://localhost:3000/message_list’ failed:

what could this be related to?

Select option depent on a other selected parent option in same page

I have a page with two selection fields. Project selection and company selection.

Existing Data for the fields. Bold are the projects, Italic the companies.

ASAS
–Fa_Test

DATA
–Fa_Test0,
–Fa_Test1,
–Fa_Test2

ELTC
–Fa_Test3,
–Fa_Test4

First view when page is loaded.

View when the first project is selected.There is only one company as standard and it cannot be changed (Text input field)

View when another project is selected.

The company selection field only appears when a project selection has been made in the first field with the following query.

<script>
$(function () {
    $("#project_ou").on( "change", function () {
        // AirbusDS
        if ($(this).val() == "empty") {
            $("#company_select").hide();
            $("#Other").hide();
        } if ($(this).val() ==  "ASAS"){
            $("#Other").show();
            $("#company_select").hide();
        } if ($(this).val() != "ASAS"){
            $("#company_select").show();
            $("#Other").hide();
        }
    });
});
</script>

The companies selection should be displayed depending on the project and without reloading the page.

The data is passed to the page with the following python code:

...
...
return render_template('portal/prov_new_device_first.html',
                      projects=projects,
                      companies=companies)

The html page part on the prov_new_device_first.html looks like this:

<div class="callout callout-warning">
     <label>Please select a Project or Division.</label><br>
     <div class="form-group">
         <select name="project_ou" class="select_proj form-control" id="project_ou">
             <option value="empty" selected>- - Select from the list - -</option>
                {% for project in projects %}
                    <option value="{{ project.name }}" id="{{ project.name }}">{{ project.name }}</option>
                {% endfor %}
        </select>
    </div>
    <div class="form-group" id="Other" style="display:none;">
        <label for="txtReason">Division (Standard)</label><br>
            {% for company in companies %}
               {% if company.destinationindicator == "ASAS" %}
                  <input type="text" value="{{ company.name }}" class="form-control" name="txtReason" disabled>
               {% endif %}
            {% endfor %}
    </div>
    <div class="form-group" id="company_select" style="display:none;">
        <label for="companyname">Please select the company where the Bootstick will be added.</label><br>
            <select name="companyname" class="form-control select_proj" id="companyname">
                <option selected>- - Select a Company</option>
                    {% for company in companies %}
                       {% if company.destinationindicator == project.name %}
                          <option value="{{ company.name }}" id="{{ company.name }}">{{ company.name }}</option>
                       {% endif %}
                    {% endfor %}
            </select>
     </div>
</div>

How can I select the correct project depent company data when I select a project?

I spent a lot of time with many options trying to transfer the project name to this place, but it did not work.

{% if company.destinationindicator == project.name %}

The destinationindicator in the company attributes contains the dependent project name.

Does anyone have any ideas on how to solve this?

Thanks in advance.

How to create a hover card animation like GitHub landing page cards in ReactJS?

I’m looking to implement a hover card animation similar to the ones seen on GitHub’s landing page. The green blob following the mouse on hover and change transform on hover. I’m working with ReactJS and wondering what would be the best approach or library to achieve this effect efficiently. Any insights, code examples, or suggested libraries would be greatly appreciated. Thanks!

video

CORS Error – Unable to replicate on most devices

For Conference Captioning, I have a few webpages that I built to help the Deaf and Hard of hearing to get live captions for in-person events: (1 & 2)

I tested it on 2 different Macs, 2 different iPhones, 2 different browsers and on a Windows as well, and when I tap “Get Live Captions”, it returns the captions using a GET API call to this end-point

Problem

I did a demo today for a teacher to implement it for students, but she was not able to pull the data on her Chrome/Safari on her Mac, she even tried to disconnect wifi and try it on her iPhone and the API call was failing with a “CORS error” according to the Chrome inspect.

She was even able to open the end point url in another tab and she was able to see the results.

Code

The front end is pretty simple, here’s the repo, I was able to use JQuery $.support.cors = true to fix the CORS error that was appearing weeks ago on my browser too.

The backend code is in C# dotnet 7, and within my ConfigureServices of the Startup.cs file, I have this:

  public class Startup
  {
    public IConfiguration Configuration { get; }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="configuration"></param>
    public Startup(
      IConfiguration configuration)
    {
      Configuration = configuration;
    }

    string  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

    /// <summary>
    /// This method gets called by the runtime. Use this method to add services to the container.
    /// </summary>
    /// <param name="services"></param>
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddCors(options =>
      {
          options.AddPolicy(
            name: MyAllowSpecificOrigins,
            policy  =>
            {
                policy.WithOrigins("https://deafassistant.com",
                                    "*");
            });
      });
      services.AddControllers();

      services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<GlobalOptions>>().Value);
      services.AddHttpContextAccessor();
      services.AddScoped<IStreamService, StreamService>();
      services.Configure<FormOptions>(options =>
      {
        options.ValueCountLimit = int.MaxValue;
      });

      services.AddSwaggerGen(c =>
      {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1.34" });
      });
    }

    /// <summary>
    /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    /// </summary>
    /// <param name="app"></param>
    /// <param name="env"></param>
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      // If we are in development mode, show the full developer exception page
      if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();

      // Force HTTPS redirection and use core routing
      app.UseHttpsRedirection();
      app.UseRouting();
      app.UseCors(MyAllowSpecificOrigins);
      // Use both authentication and authorization
      app.UseAuthentication();
      app.UseAuthorization();

      // Map controllers to the endpoints
      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers();
      });

      //swagger
      app.UseSwagger();
      app.UseSwaggerUI(c =>
      {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "API");
      });
    }

    private IDatabase GetDatabaseService(IServiceCollection services)
    {
      return services.BuildServiceProvider().GetService<IDatabase>();
    }
  }

Ask

How can I replicate the CORS error she’s facing? And how can I possibly resolve it?

Webpack 5 Issue with Build Folders Not Being Created

I have a project using HTML, CSS, and JS which I’m trying to use webpack 5 to build separate folders for /pages and /posts for HTML, a folder for my json files (/json-files), and separate files for node_modules (/vendor) and my own custom js code (bundle.js).

The build process works without errors or warnings. The /pages and /posts folders are created, as well as bundle.js (without th node_modules). However, it does not create the folder /vendor or /json-files. The node-modules are not being included in my bundle.js even if I remove the
exclude: /node_modules/ statement.

In the root directory of my project, I have /pages, /posts, /stylesheets /scripts, /media, webpack.config.js, server.js, .babel.json, /json-files, and all the other normal stuff.

I have built up a webpack.config.js file, which, as I said, works with the exception of not generating /build/json-files and /build/vendor. I have put the package.json, webpack.config.js, and the .babelrc in the githud directory below.

https://github.com/mmelester/webpack-5-config-issues.git

Any guidance would be appreciated. I am new to Webpack.

Mocking in a Jest Environment – AWS S3 Methods – Upload and getSignedUrl

file.js

/**
 * Uploads a file to an S3 bucket.
 * @param {string} bucketName - The name of the S3 bucket.
 * @param {string} key - The key under which to store the file in the S3 bucket.
 * @param {Object} body - The content of the file to be uploaded (should be JSON serializable).
 * @param {string} contentType - The MIME type of the content.
 * @returns {Promise<Object>} - A promise that resolves with the S3 upload response data.
 */
async function uploadToS3 (bucketName, key, body, contentType) {
    return new Promise((resolve, reject) => {
        const params = {
            Bucket: bucketName,
            Key: key,
            Body: JSON.stringify(body),
            ContentType: contentType,
            ContentDisposition: "inline" // Display file in browser
        };

        s3.upload(params, (err, data) => {
            if (err) {
                logger.error("Error uploading to S3:", err);
                reject(err);
            } else {
                logger.debug("Uploaded to S3:", data);
                resolve(data);
            }
        });
    });
}


/**
 * Generates a pre-signed URL for accessing an object in an S3 bucket.
 *
 * @param {string} bucketName - The name of the S3 bucket.
 * @param {string} key - The key of the object in the S3 bucket.
 * @returns {Promise<string>} A promise that resolves with the pre-signed URL.
 */
async function generateSignedUrl (bucketName, key) {
    return new Promise((resolve, reject) => {
        s3.getSignedUrl("getObject", {
            Bucket: bucketName,
            Key: key,
            Expires: PRE_SIGNED_URL_EXPIRATION_TIME // URL expiration time in seconds
        }, (err, signedUrl) => {
            if (err) {
                logger.error("Error generating pre-signed URL:", err);
                reject(err);
            } else {
                logger.debug("Pre-signed `getObject` URL generated.");
                resolve(signedUrl);
            }
        });
    });
}

/**
 * Uploads a response to an S3 bucket and generates a pre-signed URL for accessing it.
 *
 * @param {string} service - The service name.
 * @param {string} build - The build identifier.
 * @param {Object} body - The content of the response to be uploaded.
 * @param {string} format - The format of the response ("html" or "json").
 * @returns {Promise<string>} A promise that resolves with the pre-signed URL of the uploaded response.
 * @throws {Error} Throws an error if there is any issue with S3 operations.
 */
async function uploadAndGenerateSignedUrl (service, build, body, format) {
    try {
        const key = `${service}/${build}_response.${format}`;   // Construct key for the S3 object based on response type
        const contentType = format === "html" ? "text/html" : "application/json";

        // Upload to S3
        await uploadToS3(LAMBDA_RESP_BUCKET_NAME, key, body, contentType);
        logger.info("Upload to S3 completed.");

        // Generate pre-signed URL
        const signedUrl = await generateSignedUrl(LAMBDA_RESP_BUCKET_NAME, key);
        logger.info("Pre-signed URL generated.");
        return signedUrl;
    } catch (error) {
        logger.error("Error with S3 operations due to: ", error);
        throw error;
    }
}

app.get("myPath/some_build_no", function getTestResultForBuildHandler (req, res) {

    return invokeLambdaByEnvironment(`some_path/`).then((body) => {
        const htmlBody = prettyHtml(body);
        if (JSON.stringify(body).length > MAX_RESP_SIZE_THRESHOLD) {
            logger.warn("raw JSON results too large to return, returning a summary", {
                jsonBodyLength: JSON.stringify(body).length,
                service: req.params.service,
                build: req.params.build,
            });

            const service = req.params.service;
            const build = req.params.build;
            const format = req.query.format ? req.query.format.toLowerCase() : DEFAULT_FORMAT;

            uploadAndGenerateSignedUrl(service, build, body, format)
              .then((signedUrl) => {
                logger.info("Signed URL:", signedUrl);
                return redirectRequest(req, res, 302, signedUrl)    // redirect to signed URL by S3
              })
              .catch((error) => {
                logger.error("Upload and generate signed URL failed:", error);
                return endRequest(req, res, 500);   // Handle the error as needed
              });
        }else {
                // If size is less than 950000, return based on format
                if (req.query.format === "json") {
                    return endRequest(req, res, 200, body);
                } else if (req.query.format === "html") {
                    return endRequest(req, res, 200, htmlBody);
                } else {
                    return endRequest(req, res, 200, htmlBody); // Default to JSON if format is not specified or invalid
                }
            }
    }).catch((err) => {
        logger.error("failed to get results by build", {
            error: err,
        });
        logger.info("Returning 500 due to catch");
        return endRequest(req, res, 500);
    });
});

Context:

Here, function getTestResultForBuildHandler returns some response which it retrives from by invoking another lambda function. Let’s say if size of that response is more than 1 mb then it stores that value in S3 bucket and generates Pre-signed url for the same and redirect the request to that link.

I need to write test case for scenario where lambda generates more than 1 mb response. Here is sample test file, but I got stuck.

file.test.js

"use strict";

jest.mock("aws-sdk/clients/lambda");
jest.mock("aws-sdk/clients/s3");

// Some other mocks here

// Set up the mock for S3 constructor
const mockS3Constructor = jest.fn().mockImplementation(() => {
    return {
        upload: jest.fn(), // Mock the upload method
        getSignedUrl: jest.fn(), // Mock the getSignedUrl method
        promise: jest.fn().mockReturnThis(),
    }
});

describe("some_path", () => {
   test("should redirect to s3 bucket url if body is over 1mb", () => {
//            jest.setTimeout(30000);
            mockConductorLambda.mockImplementationOnce((params, cb) => {
                const conductorResponse = JSON.stringify({
                    // body generation here which is more than 1 mb
                });
                return cb(null, { Payload: conductorResponse });
            });

            mockS3Constructor().upload.mockImplementationOnce((params, callback) => {
                return callback(null, { Location: "https://example.com/pre-signed-url" });
            });

            mockS3Constructor().getSignedUrl.mockImplementationOnce((params, callback) => {
                return callback(null, "https://example.com/pre-signed-url");
            });

           // Mocking should work here - s3.upload and s3.getSignedUrl functions
           // also need handle await async if needed
           // Mocking the S3 methods for upload and getSignedUrl
//            AWS.S3.prototype.upload.mockImplementationOnce((params, callback) => {
//                callback(null, { Location: "https://example.com/pre-signed-url" });
//            });
//            AWS.S3.prototype.getSignedUrl.mockReturnValueOnce("https://example.com/pre-signed-url");


            return supertest(my_app)
                .get("/some path")
                .query({format: "html"})
                .expect(302);

        });
}

Table row flickering after useReducer update

I have a table with data, that can be edited. The edition process triggers a modification in the table with useReducer.
The problem is the styling. The table rows have a hover effect but useReducer triggers the rerender of the whole table. So after the update, it’s causing a flickering for a fraction of a second. It’s very annoying.

This is table component:

return (
        <div id={id} style={{ animation: 'bgFadeIn 0.6s ease' }}>
            <div className="changes-filters">
                {typeContent().newButton}
                {typeContent().radioButtons}
                <div className="changes-search-box">
                    <div className="changes-search-icon">
                        <GrSearch />
                    </div>
                    <input className="changes-search" placeholder="Buscar" onChange={inputChangeHandler} />
                    <div className="changes-search-icon"></div>
                </div>
            </div>
            {listData.filter.length ? (
                <table className={`table-${rowType}`}>
                    <thead>
                        <tr>
                            {headersList.map((h) => (
                                <th key={h.key} onClick={() => headerClickHandler(h.key, h.title)}>
                                    <div className="table-header">
                                        <div className="th-title">{h.title}</div>
                                        <div
                                            type="button"
                                            className={`${h.key === 0 ? 'arrow-down  arrow-active' : 'arrow-down'}`}
                                        >
                                            <BiDownArrow style={{ color: 'white' }} size={14} />
                                        </div>
                                    </div>
                                </th>
                            ))}
                            {(rowType === 'change' || rowType === 'user') && <th>Historial</th>}
                            <th>Opciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        {listData.filter.map((item) => (
                            <Row
                                key={Math.random() * 1000}
                                type={rowType}
                                data={item}
                                modifyCallback={resultModifyRow}
                            />
                        ))}
                    </tbody>
                </table>
            ) : (
                <div className="no-data">
                    <Title text={'No hay datos para mostrar.'} />
                </div>
            )}
        </div>
    );
};

The hover effect it’s just this:

tbody > tr:hover {
    background-color: #b1dffa;
}
}

Here’s the callback function:

const resultModifyRow = (response, remove) => {
        if (response.result) {
            dispatch({
                payload: {
                    type: 'modify',
                    data: response,
                    remove: remove,
                },
            });
            if (remove) {
                toast(resultMessage('delete'), { type: 'success' });
            } else {
                toast(resultMessage('modify', response.result.status), { type: 'success' });
            }
        }
        if (response.error) {
            toast(resultMessage(), { type: 'error' });
        }
    };

And here’s the reducer:

function reducer (state, action){
        const modifyList = (response, removeItem) => {
            let newItemsList = { ...listData };
            let itemIndex = newItemsList.fetched.findIndex((i) => i._id === response.result._id);
            if (removeItem) {
                newItemsList.fetched.splice(itemIndex, 1);
            } else {
                let pId = newItemsList.fetched[itemIndex].priorityId;
                newItemsList.fetched[itemIndex] = response.result;
                newItemsList.fetched[itemIndex].priorityId = pId;
            }
            return newItemsList;
        };

    switch (action.payload.type) {
            case 'modify': {
                return modifyList(action.payload.data, action.payload.remove);
            }
}

The whole reducer function it’s WAY bigger and complex. But it makes no sense to post it all, you wouldn’t undertand.
The point it’s the rerendering process causing a flickering on the table row. How can I fix this??

Thanks.

I tried adding the hover effect as a class:

.hover-effect {
    tbody > tr:hover {
        background-color: #b1dffa;
    }
}

And then toggle the class when an update it’s in process and after the dispatch function. But it keeps flickering.