Revert button text if error message is triggered

Why won’t this code revert the button text back to Place Order if an error message is triggered?

The text was changed upon clicking the button, which works fine.
But it should change back if an error message occurs upon clicking the button.
There are no console messages for the error.
This is a Stripe payment button, it’s Woocommerce.

        add_action( 'wp_footer', 'custom_checkout_jquery_script' );
        function custom_checkout_jquery_script() {
          if ( is_checkout() && ! is_wc_endpoint_url() ) :
        ?>
          <script type="text/javascript">
          jQuery( function($){
              jQuery('form.checkout').on('submit', function(event) {
                jQuery('button#place_order').text('Please Wait');
                event.preventDefault();
              });
          });
    
         //To detect woocommerce error trigger JS event
          jQuery( document.body ).on( 'checkout_error', function(){
                    var wooError = $('.woocommerce-error');
                    jQuery('button#place_order').text('Place Order');
            } );

</script>
 <?php
  endif;
}

Slider value isn’t increasing on site, looked through HTML/CSS/JS and can’t figure it out [duplicate]

This is the code i have been using. Am i missing something obvious here? The slider itself works, and so does the amount when you hit the button to continue, but the actual value does not increase. Example, if i slide it to the end it stays at (1) instead of (5)

 <!-- Start of Slider Code -->
    <div class="slidercontainerdiv">
            <span id="rangeValue">1</span>
            <Input id="amount" type="range" value="1" min="1" max="5" onChange="rangeSlide(this.value)" onmousemove="rangeSlide(this.value)">
            
    </div>
    
    
      <script>
             type="text/javascript">
             function rangeSlide(value) {
                document.getElementById('rangeValue').innerHTML = value;
              }
         </script>
         
    <!-- End of Slider HTML/JSCode --> 
    
    
    <!-- Start of Slider CSS -->
      <style> 
      
      .slidercontainerdiv {
        width:25%;
      }
      
      
        #rangeValue {
        width: auto%;
        display: block;
        text-align: center;
        font-size: 25px;
        color: white;
        font-weight: 100;
        
      }
      .range {
        width: 25%;
        height: 15px;
        -webkit-appearance: none;
        background: white;
        outline: none;
        border-radius: 15px;
        overflow: hidden;
        box-shadow: inset 0 0 5px white;
      }
      .range::-webkit-slider-thumb {
        -webkit-appearance: none;
        width: 15px;
        height: 15px;
        border-radius: 50%;
        background: white;
        cursor: pointer;
        border: 1px solid blue;
        box-shadow: -407px 0 0 400px white;
      }
    </style>
    <!-- End of Slider CSS -->

Selecting a element by it’s css selector

I’m trying to select an image element using its style selector. I wrote the line of code in Python but I’m having problems translating it to JavaScript. Here’s my attempt so far.

if driver.find_element_by_css_selector("img[style='object-fit: cover;']") is not None:
        download_url = driver.find_element_by_css_selector("img[style='object-fit: cover;']").get_attribute('src')

And here is my js attempt.

let imageArr = []

for(let post of posts) {
    await page.goto(post)
    await page.waitForTimeout(6000)

    if (await page.type("img[style='object-fit: cover;']") !== null) {

        const image = await page.evaluate(() => {
            document.querySelectorAll("img[style='object-fit: cover;']").forEach(img => {
                let imageUrl = img.getAttribute('src');
                imageArr.push(imageUrl)
            })
        })
    }
}

Disable OPTIONS request before POST in React

I have a React application based on Typescript which is hosted on my PC.
I use Spring gateway to forward requests to another microservice. GET requests are working fine but for POST requests I get:

Access to XMLHttpRequest at 'http://1.1.1.1:8080/api/support/tickets/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I’m hitting this Spring Cloud Gateway issue: https://github.com/spring-cloud/spring-cloud-gateway/issues/229

Spring cloud configuration:

@Bean
public RouteLocator routes(RouteLocatorBuilder builder, LoggingGatewayFilterFactory loggingFactory) {

    return builder.routes()
            .route("route_id",
                    route -> route
                            .path("/api/support/tickets/**")
                            .filters(f -> f.rewritePath("/api/support/tickets/(?<RID>.*)", "/support/tickets/${RID}"))
                            .uri("lb://merchant-hub-admin-service")
            )
            .build();
}

React code:

export async function getTicket(id: string) {
  return await axios.get(`${baseUrl}/support/tickets/ticket/${id}`);
}

export async function postTicket(
    data: TicketFullDTO
): Promise<AxiosResponse<TicketFullDTO>> {
  return await axios.post<TicketFullDTO>(
      `${baseUrl}/support/tickets/create`, data);
}

Do you know how I can disable OPTIONS request before POST and DELETE requests?

Range Slider not working properly in Plotly.js

I want to be able to get range slider and a selector in my graph, I have followed the example in the documentation, but I’m getting the following error:

1.- The selector dates, are still using ‘backwards’, as opposed to ‘todate’, which is a bit weird, perhaps is the fact that I’m not understanding this 100%, but I would like to get 6 and 12 months from today, is there a way to use a forward from the earliest date period?

https://jsfiddle.net/jt1o26bd/

var Deals = {
                      x: {{ deals_plot.lic_deals_date|safe }},
                      y: {{ deals_plot.lic_deals_licenses }},
                      name: 'Active Licenses',
                      type: 'bar',
                      marker: {
                                color: 'rgb(0,131,117)',

                              }
                    };
       var Leads = {
                      x: {{ deals_plot.lic_leads_date|safe }},
                      y: {{ deals_plot.lic_leads_licenses }},
                      name: 'Potential Licenses',
                      type: 'bar',
                      marker: {
                                color: 'rgb(160,220,210)',

                              }
                    };

       var data = [Deals,Leads];

       var layout = {
                title: 'Software Licenses Term',
                barmode: 'stack',
                xaxis: {
                       autorange: true,
                       rangeselector: {buttons: [
                                                     {step: 'all'},
                                                    {
                                                      count: 1,
                                                      label: 'YTD',
                                                      step: 'year',
                                                      stepmode: 'todate'
                                                    },
                                                    {
                                                      count: 6,
                                                      label: '6m',
                                                      step: 'month',
                                                      stepmode: 'todate'
                                                    }
                                                    ]},
                       rangeslider: { },
                       type: 'date',
                        tickfont:{
                           size: 14
                            },
                        },
                yaxis: {
                      tickfont:{
                                size: 14
                            }
                     }

        };

Could anyone let me know what is going on?

Fade effect blinks first time it’s triggered, but then works as intended

I’m experiencing an unwanted visual effect when changing tabs. What I want is for .policyCentre__content sections to fade out slowly, and to fade in the relevant section slowly too. However, when you change tab initially, if it’s the first time the matching policyCentre__content is loaded, it will blink in, rather than fade.

See steps to reproduce:

  1. Run the below demo (you will start off with “tab 1” active.
  2. Click “tab 2” and watch the content appear (“tab 1” content fades out, but content for “tab 2” just appears.
  3. Click back onto “tab 1”, and the content disappears and appears as intended.
  4. Click back onto “tab 2” and it now works as intended.

Unsure why the 2nd step initially just makes the content appear?

$(function() {

  function showContent(val){
    $(".policyCentre__content.active").fadeOut(500, function() {
      $(this).removeClass("active");
      $(window).scrollTop(0);
      $(".policyCentre__content[data-item='" + val + "']").addClass('active').fadeIn(500, function() {
        locked = false;
      })
    });
  }

  // prevent the UI from getting over-clicked
  let locked = false;

  $(".policyCentre__label:first, .policyCentre__content:first").addClass("active");

  $('.policyCentre__label').click(function() {
    if (locked) return;
    locked = true;
    var id = $(this).attr('data-item');
    $(".policyCentre__label").removeClass("active");
    $(this).addClass("active");
    showContent(id);
  });
  
  });
.policyCentre {
  border: 1px solid black;
  padding: 60px 0;
}
.policyCentre__label {
  display: inline-block;
  cursor: pointer;
  position: relative;
  margin-bottom: 10px;
  width: fit-content;
  display: flex;
  align-items: center;
}
.policyCentre__label:hover, .policyCentre__label.active {
  color: orange;
}
.policyCentre__content {
  display: none;
  padding-left: 50px;
}
.policyCentre__content.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<section class="policyCentre">
  <div class="container">
    <div class="row justify-content-between">

      <div class="col-2">
        <div class="policyCentre__tabs">
          <span class="policyCentre__label" data-item="tab-1">Tab 1</span>
          <span class="policyCentre__label" data-item="tab-2">Tab 2</span>
          <span class="policyCentre__label" data-item="tab-3">Tab 3</span>
        </div>
      </div>

      <div class="col-10">
        <div class="policyCentre__content" data-item="tab-1">Copy for tab 1</div>
        <div class="policyCentre__content" data-item="tab-2">Copy for tab 2</div>
        <div class="policyCentre__content" data-item="tab-3">Copy for tab 3</div>
      </div>

    </div>
  </div>
</section>

React Native prevent modal closing on overlay click

I have a Modal with a custom height which doesn’t take up the entire screen. I would like to prevent the Modal from closing when the user clicks on the overlay or outside the Modal Container. Below is a screen shot of how the modal displays

Modal Display in app

I have wrapped the Modal Component around TouchableWithoutFeedback and setting the Modal transparent to false but it still closes when the user taps outside the Modal.

Below is my current configurations of the Modal.

 onShow = () => {
        // performs slide in animation
        this.animation();
    };
      
return (

  <Modal transparent visible={visible} onShow={this.onShow}>
                <View
                    style={styles.flex}
                    onLayout={event => {
                        let {height: heightFull} = event.nativeEvent.layout;
                        this.setState({
                            height: getHeightView(heightFull, ratioHeight),
                        });
                    }}>
                   {* Modal Body * }
                    <Animated.View>
                    {* Some other content *}
                    </Animated.View>
                    {* End of Modal Body *}

                </View>
            </Modal>
)

Loop over an array and call an API for every 2 items for every 10 seconds and get data – JS

I am looping over an array and calling an endpoint to fetch data per item. I want to call every 2 items together, then wait for 10 seconds and call the next two items and so on until the list is complete. I tried a solution but its not working. Please help me on what I am doing wrong.

Here is the code.

const data = [{
  name: '1',
  id: 1,
}, {
  name: '2',
  id: 2,
}, {
  name: '3',
  id: 3,
}, {
  name: '4',
  id: 4,
}, {
  name: '5',
  id: 5,
}, {
  name: '6',
  id: 6,
}]

const result = data.reduce(async(a, c, i) => {
  let counter = 0;
  if (counter > 2) {
    setTimeout(() => {
      counter = 0;
    }, 10000)
  }
  const res = await a;
  res.push({
    name: c.name,
    id: c.id,
    title: (await (await fetch(`https://jsonplaceholder.typicode.com/posts/${c.id}`)).json()).title
  })

  await counter++;


  return res
}, Promise.resolve([]))

result.then(a => console.log(a))

How to Type a request parameter with express server

How do I Type (typescript) the attached post request to fix the error? I want to get the request body, but I can’t type it properly.

Thanks!

enter image description here

import express = require('express');
import { Request } from 'express';
import bodyParser from 'body-parser';
import { parseBMI, calculateBMI } from './bmiCalculator';
import { calculateExercises } from './exerciseCalculator';

const app = express();
app.use(bodyParser.json());

app.get('/hello', (_,res) => {
  res.send("Good day");
});

app.get('/bmi', (req,res) => {
  const weight = Number(req.query.weight);
  const height = Number(req.query.height);
  console.log(weight,height);
  try {
    const {parseHeight, parseWeight} = parseBMI(height,weight);
    const out: string = calculateBMI(parseHeight,parseWeight);
    res.json({
      weight:parseWeight,
      height:parseHeight,
      bmi:out
    });
  } catch (e) {
    res.status(4004).json(e);
  }

});
app.post('/exercises',(req: Request<Array<number>,number>,res) => {
    const body:any = req.body;
    const dailyExercises = body.daily_exercises as Array<number>;
    const target = Number(body.target);

    res.json(calculateExercises(dailyExercises,target));
  });

const PORT = 3003;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

this is only concerning the /exercises route which throws error with eslint plugin on vscode

How React works with Axios and DynamoDB

Please someone help me to understand this code. This is a part of the code for Fuse React which you can Google it. The problem, I can’t figure out is to how save data to DynamoDB. Should I use Lambda to save to DynamoDB or this code is doing everything, and I just have to change the Axios Get URI? I don’t get the path in the request:

await axios.get('/api/todo-app/todos'

Should I have an exact path on my api gateway? If yes, should I include api? or that means my api server URL?

Here is the default code without any change. Todo App sends a request via Axios:

export const getTodos = createAsyncThunk(
  'todoApp/todos/getTodos',
  async (routeParams, { getState }) => {
    routeParams = routeParams || getState().todoApp.todos.routeParams;
    const response = await axios.get('/api/todo-app/todos', {
      params: routeParams,
    });
    const data = await response.data;

    return { data, routeParams };
  }
);

And the mock api is receiving the request as following: Which I don’t know should I copy this and paste it to Lambda? Or it’s just a mock api and I dont need it at all If I use DynamoDB.

mock.onGet("/api/todo-app/todos").reply((config) => {
  const { params } = config;
  let response = [];
  if (params.labelHandle) {
    const labelId = todoDB.labels.find(
      (label) => label.handle === params.labelHandle
    ).id;

    response = todoDB.todos.filter(
      (todo) => todo.labels.includes(labelId) && !todo.deleted
    );
  } else if (params.filterHandle) {
    if (params.filterHandle === "deleted") {
      response = todoDB.todos.filter((todo) => todo.deleted);
    } else {
      response = todoDB.todos.filter(
        (todo) => todo[params.filterHandle] && !todo.deleted
      );
    }
  } // folderHandle
  else {
    let { folderHandle } = params;
    if (!folderHandle) {
      folderHandle = "all";
    }

    if (folderHandle === "all") {
      response = todoDB.todos.filter((todo) => !todo.deleted);
    } else {
      const folderId = todoDB.folders.find(
        (folder) => folder.handle === folderHandle
      ).id;
      response = todoDB.todos.filter(
        (todo) => todo.folder === folderId && !todo.deleted
      );
    }
  }

  return [200, response];
});

This seems like SO EASY to configure, But I have been working on it work 2 weeks and No luck!

Any explanation would be very helpful guys! thanks,

Zip image stream using archiver and send as express response

This is on Node/Express/Typescript. I’m trying get an image on my file system, stream it to a zip file, and then stream this zip file to the client. I have to make sure every step is streamed since this will expand to zipping up multiple files, which need to be streamed to the client as a zip.

I have the following code:

import express, { Application, Request, Response } from "express";
import fs from "fs";
import stream from "stream";
import archiver from "archiver";

app.get("/images", async (req: Request, res: Response) => {
    const r = fs.createReadStream("appicon.png");
    const ps = new stream.PassThrough();

    // stream the image
    stream.pipeline(
        r,
        ps,
        (err) => {
            if (err) {
                console.log(err);
                return res.sendStatus(400);
            }
        }
    );


    // zip the image and send it
    let archive = archiver("zip");

    output.on("end", () => {
        console.log(archive.pointer() + " total bytes");
        console.log("archiver finalized");
    })

    archive.on('error', (err) => {
        return res.status(500).send({
            message: err
        });
    })

    res.attachment('output.zip');
    ps.pipe(archive); 
    archive.pipe(res);



    archive.finalize();

});

However, when I access my /images route, I get an output.zip file which is empty.

I feel like I’m messing up the order of my pipes somehow.

What am I missing?

Why there is not my parameter so “children” in the function?

export const Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
    const dispatch = useDispatch();

    const [connected, setConnected] = useState(false);
    const [chainID, setChainID] = useState(DEFAULD_NETWORK);
    const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
    const [address, setAddress] = useState("");

    const [uri, setUri] = useState(getMainnetURI());
    const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));

    const [web3Modal] = useState<Web3Modal>(
        new Web3Modal({
            cacheProvider: true,
            providerOptions: {
                walletconnect: {
                    package: WalletConnectProvider,
                    options: {
                        rpc: {
                            [Networks.AVAX]: getMainnetURI(),
                        },
                    },
                },
            },
        }),
    );

    const hasCachedProvider = (): boolean => {
        if (!web3Modal) return false;
        if (!web3Modal.cachedProvider) return false;
        return true;
    };

    const _initListeners = useCallback(
        (rawProvider: JsonRpcProvider) => {
            if (!rawProvider.on) {
                return;
            }

            rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));

            rawProvider.on("chainChanged", async (chain: number) => {
                changeNetwork(chain);
            });

            rawProvider.on("network", (_newNetwork, oldNetwork) => {
                if (!oldNetwork) return;
                window.location.reload();
            });
        },
        [provider],
    );

    const changeNetwork = async (otherChainID: number) => {
        const network = Number(otherChainID);

        setProviderChainID(network);
    };

    const connect = useCallback(async () => {
        const rawProvider = await web3Modal.connect();

        _initListeners(rawProvider);

        const connectedProvider = new Web3Provider(rawProvider, "any");

        const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
        const connectedAddress = await connectedProvider.getSigner().getAddress();

        setAddress(connectedAddress);

        setProviderChainID(chainId);

        if (chainId === Networks.AVAX) {
            setProvider(connectedProvider);
        }

        setConnected(true);

        return connectedProvider;
    }, [provider, web3Modal, connected]);

    const checkWrongNetwork = async (): Promise<boolean> => {
        if (providerChainID !== DEFAULD_NETWORK) {
            const shouldSwitch = window.confirm(messages.switch_to_avalanche);
            if (shouldSwitch) {
                await swithNetwork();
                window.location.reload();
            }
            return true;
        }

        return false;
    };

    const disconnect = useCallback(async () => {
        web3Modal.clearCachedProvider();
        setConnected(false);

        setTimeout(() => {
            window.location.reload();
        }, 1);
    }, [provider, web3Modal, connected]);

    const onChainProvider = useMemo(
        () => ({
            connect,
            disconnect,
            hasCachedProvider,
            provider,
            connected,
            address,
            chainID,
            web3Modal,
            providerChainID,
            checkWrongNetwork,
        }),
        [connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
    );
    //@ts-ignore
    return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
};

So the dev make his code open source. and i was watching his code to understand. But i saw that he uses destructuration props but in the function why there is not the world children used? like in the example i saw when the dev uses destruction like ({name, value}) then in the function, he uses the word name and value. So why in the function there is uses of the word “children”

RUM track unused Javascript / code coverage

I am searching for a tool that tracks unused Javascript of Real Users on my website.

The problem I faced was that the Coverage Report in Dev Tools told me that there was a lot of unused JS but I didn’t know which parts of the Javascript Code I could remove without breaking the website.

The problem is extremely bad if you use a Content Management System (e.g. WordPress). Often the websites end up being very pretty but they include a lot of Javascript that is not used because you didn’t need the full functionality of the theme. To remove all the unused Javascript afterwards is extremely tedious especially if the theme was bundled with things like webpack when the code is hard to understand.

=> So I head the following idea: Is there a tool that I can use that automatically tracks which lines of JS Code my visitors run. The tool would track the data and then send me a report after a month which lines of code were unused. I would be confident to delete those lines from the code of my website because no real user ever executed them. Maybe there is a RUM tool out there that has this functionality. I am aware of Istanbul JS but I didn’t found a tool/company which offers this in a RUM fashion.

best practice to validate POST request body

My Express API exposes a POST endpoint to create a user, and i need to validate data before inserting it into database, i have two methods in mind:

Method 1: Include the model’s validation in the controller and repeat it for every model:

// controllers/users.js

exports.createUser = async function (req, res) {
    const { username, email, password } = req.body;

    /* validation logic */

    /* interact with db */

Method 2: Move the validation logic to dedicated middleware:

// middleware/validators.js

exports.validateArticle = function (req, res, next) {};

exports.validateComment = function (req, res, next) {};

exports.validateUser = function (req, res, next) {
    const { username, email, password } = req.body;

    /* validation logic */

    if (!isValid) {
        return res.statusCode(400);
    }

    next();
};
// routes/users.js

const { validateUser } = require('../middlewares/validators');

router.route('/').post(validateUser, createUser);

my concern with method 2 is that the logic for one endpoint method would be scattered among many files, but which one of these methods follow best practices ?