How do I prevent the anchor tag from overwriting my CSS style

I’m very new to all this. I’m trying to make my image into a link using the anchor tag but doing so seems to ignore the previous style I had for the image and I’m not sure why.
So my CSS looks like this:

/* Element */
*, *::after, *::before{
    box-sizing: border-box;
}

/* Variable */
:root{
     --handle-size: 3rem;
     --img-gap: .25rem;
}


.body{
   margin: 0;
}

.container{
   display: flex;
   justify-content: center;
   overflow: hidden;
}

.slider{
     --items-per-screen: 4;
     --slider-index: 0;
     display: flex;
     flex-grow: 1;
     margin: 0 var(--img-gap);
     transform: translateX(calc(var(--slider-index) * -100%));
     transition: transform 500ms ease-in-out;
}

.slider > img {
     flex: 0 0 calc(100% /  var(--items-per-screen));
     max-width: calc(100% / var(--items-per-screen));
     aspect-ratio: 16 / 9;
     padding: var(--img-gap);
     border-radius: 1rem;
 }

and my images are inside of a div which without the anchor displays correctly:

<div class = "slider">
    <img src="Icons/schitts.jpg" stlye="container" alt = "Schitts Creek">
    <img src="Icons/familyguy.jpg" alt = "Family Guy">
    <img src="Icons/gameofthrones.jpg" alt = "Game Of Thrones">
    <img src="Icons/sopranos.jpg" alt = "The Sopranos">
    <img src="Icons/southpark.jpg" alt = "South Park">
    <img src="Icons/prisonbreak.jpg" alt = "Prison Break">
    <img src="Icons/curbyourenthusiasm.jpg" alt = "Curb Your Enthusiasm">
    <img src="Icons/americandad.jpg" alt = "American Dad">
    <img src="Icons/sinister.jpg" alt = "Sinister">
    <img src="Icons/superbad.jpg" alt = "Superbad">
    <img src="Icons/hangover.jpg" alt = "The Hangover">
    <img src="Icons/midsommar.jpg" alt = "Midsommar">
</div>

When I add the anchor tag between an image, it ignores the previous styles I had while the other images without the anchor tag remain in the correct style.
How do I keep the layout of everything the same while allowing the image to contain a link?

Without Anchor tag

With Anchor tag around first image

onClick function calling a funciton declaration doesn’t work [duplicate]

I am trying to implement an onclick function to an html element (which results in the simulation of rolling a dice from 1 – 6) and figured out a way to that. But while I was trying to get to work, I came across a path that just wont work and I can’t figure out why.

This approach is working – I just calling methods inside the eventListener and it sucessfully returns a random number between 1 & 6 in the console:

const dice = document.querySelector('.btn--roll');     
dice.addEventListener('click', function () {
      const number = Math.trunc(Math.random() * 6) + 1;
          console.log(number);
          return number;
        });

But I just can’t figure out why the second approach is not working. I am defining a function beforehand and just calling it inside the eventListener. But the console wont print anything when I click on the button.

 function rollDice() {
      console.log(Math.trunc(Math.random() * 6) + 1);
    }
 const dice = document.querySelector('.btn--roll');
 dice.addEventListener('click', rollDice());

Material UI fill in select component based on outside source

I am writing a program that has a select field with options 1, 2, and 3. Users can choose between the 3. However another select that has an object that has a value relating to that select.

enter image description here

enter image description here

For example, if I choose ‘ten’ on the ‘Cycles’ select it is associated with an object (data) that contains a value associated with the type field. So if I select ‘Ten’, it has an object value data[‘type’] that would be 1. How can I have it so when I select a cycle option it will fill in the ‘type’ field.

              <FormControl
                sx={{ minWidth: 200 }}
                variant="standard"
                size="small"
              >
                <InputLabel>Type</InputLabel>
                <Select disabled={radioEdit}>
                  <MenuItem value="">
                    <em>None</em>
                  </MenuItem>
                  <MenuItem value={1}>1</MenuItem>
                  <MenuItem value={2}>2</MenuItem>
                  <MenuItem value={3}>3</MenuItem>
                </Select>
              </FormControl>

Here is the code I am using to declare my ‘type’ select component. The object is called data[‘type’]. How can I have that ‘type’ field empty until I select an option from ‘Cycles’ then fill it in automatically? Let me know if you need any other information, been stumped on this for awhile.

Run function before tab containing iframe(declared as web accessible resources) is closed Manifest v3

I have a manifest that looks somewhat like this:

"web_accessible_resources": [
   {
     "resources": [
       "script_injector.html",
       "script2.html"
     ],
     "matches": [
       "<all_urls>"
     ]
   }
 ],
 "content_scripts": [
   {
     "matches": [
       "<all_urls>"
     ],
     "js": [
       "new-content.js"
     ]
   }
 ],

In the new-content.js I have set an iframe:

let ifr = document.createElement('iframe');
ifr.setAttribute('allow', "microphone; camera; display-capture;");
ifr.style.display = 'none';
ifr.src = chrome.runtime.getURL('script_injector.html');
document.body.appendChild(ifr);

Script_injector.html looks like this.

<script src='script_injector.js'></script>

Script_injector.js

This file has data that needs to be saved before the tab containing the iframe is closed. The data is MediaRecorder blobs which is available only when the Mediarecorder is stopped. I need to save the data if the tab is closed and i have tried putting the save data inside the below function :

chrome.tabs.onRemoved.addListener(function (tabId, changeInfo, tab) {
savedata()
})

chrome.tabs.onRemoved is not firing at all when I close the tab. Which means the data that is recorded is lost.

Note that: I cannot use MediaRecorder in service worker in Manifest v3 because Media and Audio APIs are not allowed. So I use it this way. I am unaware about other ways but i think it’s the only method.

How do I save the data before the page containing the iframe is closed?

What would be the best practice to use JavaScript function in reactable?

In reactable it is possible to use JavaScript functions, like in this example:

reactable(iris, columns = list(
  Species = colDef(
    cell = JS("function(cellInfo) {
      return '<b>' + cellInfo.value + '</b>'
    }")
  )
))

However, all examples I saw in the documentation use string passed to the JS() function. I think that taking into account the readability and conveniences, it would be better to store the JS function in separate .js file. Is it true? And if yes, how to achieve this? I mean – how to call then this function? Based on the example above.

Why is Google Analytics and Optimize not reporting my experiment traffic?

Not sure why this isn’t working. But i have a Google Optimize experiment setup…

It changes the string in a title

The variant page loads correctly

The Optimize experiment itself connected properly to my app

I added the gtag.js script to my app through Google Tag Manager

<script type="text/javascript" id="" src="https://www.googletagmanager.com/gtag/js?id=UA-12345678-1"></script>

And

window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag("js",new Date);gtag("config","UA-12345678-1");

It is a custom html tag in GTM which i got warned not to do, but not sure how else to put it in.

The page is tracking as a page viewed in the main GA real time info. But when i click “View my report in Analytics” in Optimize, it takes me into GA, where there’s no hits being recorded. It’s just 0% bounces / activity.

What have i done wrong?

Clicking anywhere on the page besides the 3 menu items hide any visible menu

  The corresponding dropdown element should display below it
  BONUS: Clicking anywhere on the page besides the 3 menu items
  hide any visible menu item
  Look into the matches() function
  Hamburger icon / nav elements:
  When user clicks hamburger icon, side menu should be displayed
  When user clicks “close” button in side menu, it should be hidden again
  You should only be adding JS here!
  My HTML and CSS are identical in the starter & solution code

  HTML
   <ul class="nav">
   <li id="menu-1-button">Why Slack?</li>
   <li id="menu-2-button">Solutions</li>
   <li id="menu-3-button">Resources</li>
   <li>Pricing</li>
   </ul>
   </section>
   <div class="nav-right">
   <p class="workspaces">Your Workspaces</p>
   <div class="hamburger-menu" id="menu-trigger">
   <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/hamburger.svg"         alt="Hamburger icon">
   </div>
   </div>
   </header>

   <!--Main content-->
   <section class="placeholder"></section>

   <!--Side menu-->
   <aside class="side-menu-position side-menu-design" id="side-menu">
   <header class="side-menu-header">
   <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/slack.svg"         alt="Slack logo">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/x.svg" alt="Close     this menu" id="menu-close">
    </header>
    <ul class="side-menu-content">
     <li>Why Slack?</li>
     <li>Pricing</li>
     <li>About Us</li>
     <li class="side-menu-workspace">Your Workspaces</li>
     <li class="side-menu-download">Download Slack</li>
     </ul>
     </aside>

    <!--Dropdown Menus, notice how they are asides listed just inside the body - no deeper -->
     <aside class="dropdown-menu" id="menu-1">
     <h2 class="menu-header">About the Product</h2>
     <ul class="menu-item-list">
     <li><a href="#">How it works</a></li>
     <li><a href="#">Security</a></li>
      <li><a href="#">Customers</a></li>
    <li><a href="#">Enterprise</a></li>
    </ul>
    </aside>

    <aside class="dropdown-menu" id="menu-2">
   <h2 class="menu-header">Slack for Every Team</h2>
   <ul class="menu-item-list">
   <li><a href="#">Engineering</a></li>
   <li><a href="#">IT</a></li>
    <li><a href="#">Customer Support</a></li>
   <li><a href="#">Project Management</a></li>
   <li><a href="#">Sales</a></li>
   <li><a href="#">Marketing</a></li>
   <li><a href="#">Human Resources</a></li>
   </ul>
   </aside>

   <aside class="dropdown-menu" id="menu-3">
   <h2 class="menu-header">Go Further With Slack</h2>
   <ul class="menu-item-list">
   <li><a href="#">Download</a></li>
   <li><a href="#">Blog</a></li>
  <li><a href="#">Help Center</a></li>
  <li><a href="#">e-Books</a></li>
  <li><a href="#">Reports</a></li>
  <li><a href="#">API</a></li>
  </ul>
 </aside>

 CSS

 body {
 font-family: 'Lato', sans-serif;
 color: #454545;
}

.placeholder {
 background: lightslategray;
 height: 100vh;
}

.global-header {
 background-color: white;
 display: flex;
 flex-direction: row;
 justify-content: space-between;
 height: 40px;
 padding: 15px 25px;
 width: calc(100% - 50px);
 }

/* NAV */

.nav-left {
 align-items: center;
 display: flex;
}

.logo {
display: flex;
 align-items: center;
 }

 .logo svg {
  width: 150px;
 }

 .nav {
  display: none;
 flex-direction: row;
 align-items: center;
 margin: 0;
 padding-left: 0;
}

 @media (min-width: 1085px) {
 .nav {
 display: flex;
 }
}

   ul {
   list-style: none;
   }

    .nav li {
      font-size: 14px;
     margin: 0 20px;
     cursor: pointer;
    }

     .nav-right {
      align-items: center;
      display: flex;
      justify-content: flex-end;
      margin-right: 45px;
     }

   /* DROPDOWN MENU */

   .dropdown-menu {
    background-color: white;
    box-shadow: 0 0 2rem rgba(0,0,0,.1); 
    /* `display: none` hides the element when the page loads - how could we change    this    when our JS event takes place? */
     display: none;
     padding: 15px;
     position: absolute; /* pops element up in the dom */
     top: 60px;
     width: 250px;
     z-index: 10;
   }

     /* element has this class and ID */
        .dropdown-menu#menu-1 {
        left: 190px;
     }

     .dropdown-menu#menu-2 {
     left: 290px;
     min-width: 400px;
    }

    .dropdown-menu#menu-3 {
     left: 390px;
     min-width: 400px;
    }

  .menu-header {
   font-size: 12px;
    margin: 0;
    padding: 0 10px 8px 10px;
    text-transform: uppercase;
   }

  .menu-item-list {
   margin: 0;
   padding-left: 0;
  }

  /* https://developer.mozilla.org/en-US/docs/Web/CSS/columns 
  
Guide to Responsive-Friendly CSS Columns
*/ #menu-2 .menu-item-list, #menu-3 .menu-item-list { column-count: 2; column-gap: 20px; } .menu-item-list li a, .menu-item-list li a:visited, .menu-item-list li a:focus { color: #454545; display: block; padding: 10px; text-decoration: none; } .menu-item-list li a:hover { background-color: rgb(242,242,242); color: #1264a3; } /* Fade-in header */ #fade-in-header { display: none; position: fixed; top: 0; } #top-nav { position: fixed; } .show { display: block; } /* SIDE MENU */ .workspaces { background-color: #611f69; border-radius: 10px; color: white; cursor: pointer; display: none; padding: 8px 16px; transition: all 420ms ease-in-out; } /* Notice you can do a hover state on an element, not just <a> links */ .workspaces:hover { background-color: #4a154b } @media (min-width: 1085px) { .workspaces { /* Hidden below 1085px - see above rule */ display: block; } } .hamburger-menu { display: block; /* display:none starts to show up with responsive */ cursor: pointer; } @media (min-width: 1085px) { .hamburger-menu { display: none; } } /* OFF CANVAS MENU * Slack has an image with a translucent bg which combines bg color and image together * position: fixed with 0,0,0,0 positions streches across the viewport * z-index: 2 keeps it on top of the rest of the page * I'm breaking the side-menu parent into two styles, one position and on design, so you can see how this looks better * You don't have to do it this way at all...but it helps to see the separation of concerns here */ .side-menu-position { padding-top: 25px; position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 2; } .side-menu-design { background-color: #611f69; background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/sidebar-background.png'); background-size: 1300px 700px; background-repeat: repeat; cursor: pointer; opacity: 0; transform: translateX(100%); transition: 0.4s ease-in-out; } /* on top we need spacing from the border, so we have to use padding */ /* but we also want that bottom margin to bleed to the edge, so no margins here */ .side-menu-header { border-bottom: 1px solid rgba(255,255,255,.1); /* based on slack look, very faint */ display: flex; justify-content: space-between; padding: 0 25px 25px 25px; } /* Main content is pretty easy for layouts, pattern you'll see in web dev */ /* The more text an element has, the easier it is to layout - BAM wisdom bomb! */ .side-menu-content { color: #fff; font-size: 24px; /* could use ems here too */ margin: 25px; padding-left: 0; } .side-menu-content li { list-style: none; margin-bottom: 25px; } .side-menu-workspace { margin-bottom: 8px; text-align: center; } .side-menu-download { background-color: #fff; color: #611f69; padding: 15px 0; text-align: center; width: 100%; } /* Sticks the nav to the top of the page */ #top-nav { position: fixed; } /* Animation classes */ .show-menu { opacity: 1; transform: translateX(0%); } JavaScript const menu1Button = document.getElementById('menu-1-button'); const menu2Button = document.getElementById('menu-2-button'); const menu3Button = document.getElementById('menu-3-button'); // We'll also assign all 3 of our menu dropdown elements to variables const menu1Dropdown = document.getElementById('menu-1'); const menu2Dropdown = document.getElementById('menu-2'); const menu3Dropdown = document.getElementById('menu-3'); // Note that we are never reassigning the value of any of these variables - which is why we're using the `const` keyword instead of the `let` keyword // Okay. Let's talk through what functionality we want for one button. Let's start with the first menu element - "Why Slack?" - we've stored that as `menu1Button` variable above. // So we'll have something like: // menu1Button.addEventListener("someevent", someFunction);

// What’s the event? It’s when the user clicks that element. What event is that in JS? It’s the “click” event – https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event

 // So now we have:
 // menu1Button.addEventListener("click", someFunction);

 // Now we need the function to run! Let's not name it `someFunction` - we'll name it after the functionality we want it to execute! We want it to display the first dropdown menu element - so how about `displayMenuOne`?

 // So now we have:
 // menu1Button.addEventListener("mouseover", displayMenuOne);

  // Now we just need our `displayMenuOne` function!
  // It should *display* the element with ID "menu-1" - stored as `menu1Dropdown` variable above.
  // How can we edit that element to display it? We *could* use the "style" property (remember when we did `document.body.style.backgroundColor` in the color switcher activity in Lesson 10?).
  // However, it's easier to use CSS classes - and we have this `.show` rule in our CSS... so let's just add the "show" class to the "menu1Dropdown" element  

 // function displayMenuOne() {
 //   menu1Dropdown.classList.add("show");
// }

 // Last piece: what if one of the other dropdowns is being displayed? Remember - we don't always want to rely on the initial state of our page. The initial state is that none of the dropdowns are displayed, but what if I've clicked on `menu1Button` when the second menu is already visible?

 // Let's make sure to remove the `show` class on our other 2 dropdown elements, whether or not that class is present on the element.

// So we end up with:

 menu1Button.addEventListener("click", displayMenuOne);

 function displayMenuOne() {
 menu1Dropdown.classList.add("show");
 menu2Dropdown.classList.remove("show");
 menu3Dropdown.classList.remove("show");
}

// Let's repeat this for our other 2 menu button elements.
 menu2Button.addEventListener("click", displayMenuTwo);
 menu3Button.addEventListener("click", displayMenuThree);

 function displayMenuTwo() {
 // show menu 2
 menu2Dropdown.classList.add("show");
 // hide menus 2 and 3 if they are open
  menu1Dropdown.classList.remove("show");
  menu3Dropdown.classList.remove("show");
  }

  function displayMenuThree() {
  // show menu 3
  menu3Dropdown.classList.add("show");
  // hide menus 1 and 2 if they are open
  menu1Dropdown.classList.remove("show");
  menu2Dropdown.classList.remove("show");
  }

 // SIDE MENU

 // There's a menu icon present at or below a viewport width of 1085px.
// It has the ID of `menu-trigger`.
// Let's assign it to a variable.

 const menuDisplayButton = document.getElementById('menu-trigger');

// What event are we listening for on that element?
// A click!

 menuDisplayButton.addEventListener("click", displaySideMenu);

// When the side menu is visible, it has a close button with ID `menu-close`.
// Let's add a click listener for that element that will hide the side menu.

 const menuCloseButton = document.getElementById("menu-close");
 console.log(menuCloseButton);
 menuCloseButton.addEventListener("click", hideSideMenu);

 // Now we just need these 2 functions - `displaySideMenu` and `hideSideMenu`
// The class that displays our side menu element is `show-menu`
// so `displaySideMenu` will add that class to the side menu element
// and `hideSideMenu` will remove that class

const sideMenu = document.getElementById('side-menu');

function displaySideMenu() {
sideMenu.classList.add("show-menu");
}

function hideSideMenu() {
sideMenu.classList.remove("show-menu");
}

The corresponding dropdown element should display below it
BONUS: Clicking anywhere on the page besides the 3 menu items
hide any visible menu item
Look into the matches() function
Hamburger icon / nav elements:
When user clicks hamburger icon, side menu should be displayed
When user clicks “close” button in side menu, it should be hidden again
You should only be adding JS here!
My HTML and CSS are identical in the starter & solution code

Please focus on the bonus part

How to Re-render a Map created with React Leaflet when Incoming Props Change

I am stuck trying to trigger a re-render of the upon changes in props.

The App.js file initializes state and sets the latitude and longitude to empty strings and the state is updated with the results of an API call. The new values of state are then passed to the for its use in determining the position of the marker on the map.

The challenge I am having now is how to ensure that the newProps received in the component leads to a re-render of the component.

The code in APP.js is as follows

import React from "react"
import './App.css';
import AddressHeader from "./Components/AddressHeader"
import AddressDetails from "./Components/AddressDetails"
import AddressMap from "./Components/AddressMap"

export default function App () {

  //State will be created here in the APP.js file and passed to child components via props
  const [visitorDetails, setVisitorDetails] = React.useState({
    ipAddress : "",
    city: "",
    timezone: "",
    ISP: "",
    latitude: "",
    longitude: ""
 });

 React.useEffect(() => { //Fetch data from the API only once, hence the dependencies array has the element 0
    fetch("https://geo.ipify.org/api/v2/country,city?apiKey=at_weFpeQS6scjef5CE5Bf9il4OXCNfM")
    .then(res => res.json())
    .then(data => setVisitorDetails({      
          ipAddress: data.ip,
          city: data.location.city,
          timezone: data.location.timezone,
          ISP: data.isp,
          latitude: data.location.lat,
          longitude: data.location.lng
       
    }));
 }, [0])

  return (
    <section>
      <AddressHeader />
      <AddressDetails 
        ipAddress = {visitorDetails.ipAddress}
        city = {visitorDetails.city}
        timezone = {visitorDetails.timezone}
        ISP = {visitorDetails.ISP}
        />
      <AddressMap 
        latitude = {visitorDetails.latitude}
        longitude = {visitorDetails.longitude}
      />
    </section>
  )
}

And the code in component is as follows

import React from "react"
import map from "../ComponentStyle/Map.module.css"
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'



export default class AddressMap extends React.Component {

    constructor () {
        super()
        this.state = {
            latitude: "",
            longitude: ""
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
      if(nextProps.latitude !== this.props.latitude) {
        return true
      } 
    }

    render () {
        return (
            <MapContainer center={[this.state.latitude, this.state.longitude]} zoom={13} scrollWheelZoom={false} className = {map.mapContainer}>
            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position = {[this.state.latitude, this.state.longitude]} >
               <Popup>
                  A test marker and popup
               </Popup>
            </Marker>
          </MapContainer>
        )
    }
}

how to open a html file by onclick?

I am trying to open a html file when I click on an image. I like to open the html file in my current browser. Is that possible?



const clock = document.createElement('div')

clock.innerHTML = '<img src="https://png.pngtree.com/png-vector/20190912/ourlarge/pngtree-clock-icon-in-flat-style-png-image_1728101.jpg" height = "60px" width="60px"alt="NI">';

clock.onClick = function () {
    window.open('file:///Users/puyang/Desktop/clock/popup.html')
}
document.body.append(clock)


Getting a stored jwt cookie and verifying it

I’m trying to make it so that some pages only render whenever an user is logged in. However, I can’t seem to find any documentation on how to retrieve cookies using vue.js. My project is being made with the mevn stack. And I saved the user cookie with:

        res.cookie('token', token, {
            maxAge: 24 * 60 * 60 * 1000,
            httpOnly: true
        });

The problem I’m facing now is retrieving this cookie, so that I can verify wether the user is logged in. I can’t find anything on how to do this, so I’m asking it here.

/pages/crash.vue

data() {
        return {
            foo: false,
        };
    },
    mounted() {
        // Get cookie
        // If cookie is valid 
        // Set this.foo to true
        if (this.foo) {
            ...
        } else {
            window.location.href = '/login'
        }
    },

how to filter child elements in jquery

trying to create a search filter based on an list in a razor view:

<input class="form-control" id="foodSearch" type="text" placeholder="Search here...">
<br>
<ul class="list-group" id="foods">
    @foreach (var f in @Model)
    {
        <li>
            <div id="food">
                <p">@f.Name</p>
                <small>@f.prepTime, @f.price </small>
            </div>
        </li>

    }
</ul>


$("#foodSearch").on("keyup", function () {
        var value = $(this).val().toLowerCase();
    $("#foods li div").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });

so essentially I am trying to filter based on the values contained within the ‘p’ and ‘small’ tags, and then only that ‘parent’ div be left in the search

Write multiple values from json file into HTML table with Javascipt

Heyy!

I have a small problem and I am still a beginner. That’s why I haven’t found a solution yet. ^^

There is a json file with multiple values. I would like to write the values from the file into an HTML table with Javascript (not php!).


Here is an example:

Json File:

{
   "628e191673ae8f7750c62fce": {
     "name": "John",
     "surname": "Smith",
     "age": "24"
   },
   "628e1fd0d27981c6250d886c": {
     "name": "Fred",
     "surname": "Bloggs",
     "age": "32"
   },
   "628e20c805f38641bdc08d7d": {
     "name": "Joe",
     "surname": "Harris",
     "age": "27"
   }
}

The table should then look like this:

Name Surname Age
John Smith 24
Fred Bloggs 32
Joe Harris 27

What is the best way for me to do this with Javascript?
Thank you in advance. 🙂

How to mock NODE_ENV in unit test using Jest

I want to set NODE_ENV in one of the unit test but it’s always set to test so my tests fails.

loggingService.ts

...

const getTransport = () => {
  if (process.env.NODE_ENV !== "production") {
    let console = new transports.Console({
      format: format.combine(format.timestamp(), format.simple()),
    });
    return console;
  }

  const file = new transports.File({
    filename: "logFile.log",
    format: format.combine(format.timestamp(), format.json()),
  });
  return file;
};

logger.add(getTransport());
const log = (level: string, message: string) => {
  logger.log(level, message);
};

export default log;

loggingService.spec.ts

     ...
    describe("production", () => {
        beforeEach(() => {
          process.env = {
            ...originalEnv,
            NODE_ENV: "production",
          };
    
          console.log("test", process.env.NODE_ENV);
          log(loglevel.INFO, "This is a test");
        });
    
        afterEach(() => {
          process.env = originalEnv;
        });
    
        it("should call log method", () => {
          expect(winston.createLogger().log).toHaveBeenCalled();
        });
    
        it("should not log to the console in production", () => {
          expect(winston.transports.Console).not.toBeCalled();
        });
    
        it("should add file transport in production", () => {
          expect(winston.transports.File).toBeCalledTimes(1);
        });
      });
...

How can I set process.env.NODE_ENV to production in my tests preferably in the beforeEach such that the if block in my service is false and the file transport is returned. I have omitted some code for the sake of brevity.

What is more performant way to request an image using Axios and proccess it (Blob vs Buffer)?

I am looking for a workaround to authenticate image requests in a RESTful app, see JWT-based authentication for tags?. I’ve come to a solution which uses Axios to grab the images via api routes (where the auth layer is already set).

I’ve tested two ways to grab a binary resource via axios, one is using a blob the second an arraybuffer, they both seemed to work fine:

Blob / FileReader, ReadAsDataUrl:

const SecuredImageAsBlob = ({ path, ...props }: Props) => {
  const [imageDataUrl, setImageDataUrl] = useState<string | ArrayBuffer | null>()
  useEffect(() => {
    axiosWithAuthHeaders
      .get(`/securedimage/${path}`, {
        responseType: "blob",
      })
      .then(response => {
        var reader = new window.FileReader()
        reader.readAsDataURL(response.data)
        reader.onload = function () {
          setImageDataUrl(reader.result)
        }
      })

    return () => {}
  }, [path])
  return imageDataUrl ? <img src={String(imageDataUrl)} {...props} /> : null
}

vs Buffer / toString("base64"):

const SecuredImageAsBuffer = ({ path, ...props }: Props) => {
  const [base64string, setBase64string] = useState<string | null>()
  useEffect(() => {
    axiosWithAuthHeaders
      .get(`/securedimage/${path}`, {
        responseType: "arraybuffer",
      })
      .then(response => {
        const buffer = Buffer.from(response.data, "binary").toString("base64")

        setBase64string(buffer)
      })

    return () => {}
  }, [path])
  return base64string ? <img src={`data:image/png;base64,${base64string}`} {...props} /> : null
}

But which one is more performant? I would say the Blob with FileReader() and readAsDataUrl, because it is reading a stream, so it can start to paint the image before it is fully loaded (which is close to the native <img /> behaviour). Buffer, on the other hand, has to be fully loaded and then converted to base64 before it can be shown as image, and I also guess it would take more memory because the size would be bigger. But I might be completely wrong, so feel free to correct me!

What do you thing? Blob / FileReader, Buffer / base64, or some other way I completely missed?