Show all collections for category on shopify

I am trying to build a collection page on shopify that mimics the prada.com navigation. I am a bit confused how to implement this because what I want to do is have this on a collection template. I seen some code snippets showing nested navigation and they create a collection list page using the linklist object.

What I am trying to implement is lets say you have a site with jewellery and clothing. In the menu when you click clothing you see ‘shirts’ and ‘pants’.

Here you have two collections in clothing:

|-Jewelry
|-Clothing
  |-shirts
  |-pants 

How would I implement this like so:

|-Jewelry
|-Clothing
  |-all clothing
  |-shirts
  |-pants

What I am trying to accomplish is when you click on shirts you are on a collection template with 3 buttons at the top: ‘all clothing’, ‘shirts’, ‘pants’ and it would show the ‘shirts’ button is selected. If you clicked on all clothing you would still be on the collection template but now shirts and pants would both be shown.

This is a link to an example
https://www.prada.com/de/en/women/ready_to_wear.html

Note how at the top there is a button to show all and user can select a subset.

How to properly import method from ES6 default method (out-of-scope variables)

I need to mock a function from the following defaultly exported object:

const ajax = {
  ...
  json: (custom function)
  ...
}

export default ajax

The only we I have found is this:>

jest.mock('mergado/ajax', () => ({
    __esModule: true,
    default: {
        json: jest.fn()
            .mockReturnValueOnce(
                new Promise((resolve) => 
                  resolve(testCategories))
            )
            .mockReturnValueOnce(
                new Promise((resolve) => 
                  resolve(testSearchResult))
            ),
    },
}))

I need to mock values returned by the mocked function, hence the testCategories and testSearchData. However I cannot do that here due to this error:

jest.mock('mergado/ajax', () => ({
    __esModule: true,
    default: {
        json: jest.fn()
            .mockReturnValueOnce(
                new Promise((resolve) => resolve(testCategories))
            )
            .mockReturnValueOnce(
                new Promise((resolve) => resolve(testSearchResult))
            ),
    },
}))

I know that normally I would do that in a beforeAll section of code, but I haven’t found any way to refer to mock function correctly. When I refer outside function, I ran into a “cannot access before initilialization” problem:

const mockedFetch = jest.fn()
    .mockReturnValueOnce(
        new Promise((resolve) => resolve([]))
    )
    .mockReturnValueOnce(
        new Promise((resolve) => resolve([]))
    )

jest.mock('mergado/ajax', () => ({
    __esModule: true,
    default: {
        json: mockedFetch,
    }}))

How can I mock the function in a way that would allow me to use imported test data?

I have implemented function without using function key but not able to print the result

I have written one function, without using function keyword.
if age is above 15 take the value and push into one array. I have done that but i am not able print the result.Kindly any one help on this.

my code

<script>
var age = ["14", "20", "25"];
const response = howMany(people) {
  let oldCitizen = [];
  for (let i = 0; i < people.length; i++) {
   if (people[i] >=15) {
    oldCitizen.push(people[i]);
   }
  }
  return oldCitizen;
}
console.log(howMany(age));
</script>

Getting Error

(index):3 Uncaught SyntaxError: Unexpected token ‘{‘ (at (index):3:34)

I know below code also will work, but i need without function keyword i wants to implements one function and print the result.

<script>
var age = ["14", "20", "25"];
function howMany(people) {
  let oldCitizen = [];
  for (let i = 0; i < people.length; i++) {
   if (people[i] >=15) {
    oldCitizen.push(people[i]);
   }
  }
  return oldCitizen;
}
console.log(howMany(age));
</script>

Dynamically loading SVG React Component

Trying to dynamically load SVG’s but getting a Runtime Error, and not sure what the issue is. Can anyone help out?

Component:

import React, { useEffect, useRef } from "react";
import { IIcon } from './IIcon';
import {
    DEFAULT_ASSET_ICON_FOLDER,
} from '@/constants/default';

function Icon({name}: IIcon) {
  const ImportedIconRef = useRef();

  useEffect(() => {
    const importIcon = async () => {
      try {
        ImportedIconRef.current = (
          await import(`${DEFAULT_ASSET_ICON_FOLDER}/${name}.svg`)
        ).ReactComponent;
      } catch (err) {
        // @TODO - Log error somewhere
      }
    };
    importIcon();
  }, [name]);

  const SvgIcon = ImportedIconRef.current;

  return (
    <SvgIcon />
  );
}

export default Icon;

Usage:
I just want to pass in a string based reference to the file name.

<Icon name="DELETE" />

Error
This is the error I’m getting back, referring to Element type is invalid

Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Icon`.

Fixture variable unable to access inside the It block

///

import ShowPagePOM from “../../pageObjects/ShowPagePOM”
import SelectItems from “../../fixtures/SelectItems.json”
//var data1;

describe(‘Validate all basic funcationality of Website’, () => {
const showPage = new ShowPagePOM()

before(function() {
   
    cy.visit(Cypress.env("login_url"))
    cy.fixture('SelectItems').then(function(data){
         this.data1 = data

    })
    
   })
   
it('select cart items',function()  {
    
   
    showPage.getShowBtn().click()
    showPage.getItenName().each((e1,index,length) => {

            this.data1.items.forEach(function(elements){
                if(e1.text().includes(elements)){
                    showPage.getItemAddBtn().eq(index).click()
                }
               
            })

    })
    
})

it('Validate add to cart', ()=> {
    console.log(this.data1.items.length)
    showPage.getCart().then(function(element){
        const cartText = element.text()
        const s1 = cartText.split('(')
        const s2 = s1[1].split(')')
        
        expect(parseInt(s2[0]),this.data1.items.length)
        
      })

})

})

output

Possibility to pass hash symbol in ‘tel:XXXXXXXX’ function [duplicate]

I have a window.open(`tel:123#4455`, '_self') command on button which opens “Send to phone” popup, but Chrome browser cuts # and everything past it, so i am left with 123 in my Phone app. Is it possible to pass a number as a whole? I tried to replace # with %23 – but instead of the “Send to phone” popup, the “Open in FaceTime” popup appears, this is not what is needed

Add mouse drag to touchstart function

I’ve created a slider. I have a touch event allow the user to slide using touch but the mouse event isn’t working.

I’d like a mouse drag option as a fall back option. I thought a mouse event would work as standard.

I have the touch working but I can’t get the mouse touch to work with it.

Here’s the code. What am I doing wrong?

function swipedetect(el, callback){
  
    var touchsurface = el,
    swipedir,
    startX,
    startY,
    distX,
    distY,
    threshold = 50, //required min distance traveled to be considered swipe
    restraint = 100, // maximum distance allowed at the same time in perpendicular direction
    allowedTime = 300, // maximum time allowed to travel that distance
    elapsedTime,
    startTime,
    handleswipe = callback || function(swipedir){}
  
    touchsurface.addEventListener('touchstart', function(e){
        var touchobj = e.changedTouches[0]
        swipedir = 'none'
        dist = 0
        startX = touchobj.pageX
        startY = touchobj.pageY
        startTime = new Date().getTime() // record time when finger first makes contact with surface
        e.preventDefault()
    }, false)

    // Bind the functions...
    el.onmousedown = function () {
        _drag_init(this);
    return false;
    };
  
    touchsurface.addEventListener('touchmove', function(e){
        e.preventDefault() // prevent scrolling when inside DIV
    }, false)
  
    touchsurface.addEventListener('touchend', function(e){
        var touchobj = e.changedTouches[0]
        distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
        distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
        elapsedTime = new Date().getTime() - startTime // get time elapsed
        if (elapsedTime <= allowedTime){ // first condition for awipe met
            if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
                swipedir = (distX < 0)? 'left' : 'right' // if dist traveled is negative, it indicates left swipe
            }
            else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
                swipedir = (distY < 0)? 'up' : 'down' // if dist traveled is negative, it indicates up swipe
            }
        }
        handleswipe(swipedir)
        e.preventDefault()
    }, false)
}
  
//USAGE:
var input = Inputs.Input;
const el = input.getDOMElement();

swipedetect(el, function(swipedir){
    if (swipedir =='left') {
        // alert(swipedir);
        Outputs.swipeLeft()
       
    }
    else if (swipedir === 'right') {
        // alert(swipedir);
        Outputs.swipeRight()
        
    }
});
Outputs.Done ();

How to redirect based on hcaptcha resonse?

Looking for solution to redirect to a specifc url based on hcaptcha results:

<script src="https://hcaptcha.com/1/api.js" data-size="invisible" async defer></script>
<div class="h-captcha" data-sitekey="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"></div>

Please advise!

How can I prevent Gatsby’s router from re-writing the path for a page?

For various historical reasons, I’m trying to serve a page within a sub-directory of a Gatsby v3 site as if it were the top-level page from a different domain.

I’m using a Cloudflare Worker to determine the domain of the request and then proxies either the top level page, or the sub-directory page, serving the sub-directory page as if it were the root page.

When the top level domain is accessed the page loads as expected however Gatsby re-writes the path to include the sub-directory – which is not what I’m after.

Example, in the Gatsby project:

/src/pages/index.js  <--- the "normal" top level page, i.e. www.example.com/
/src/pages/example/index.js  <---- the page I want for www.some-other-example.com/

Behaviour at the moment:

  • www.example.com/
    • loads /src/pages/index.js – expected
    • path in browser / – expected
  • www.some-other-example.com
    • loads src/pages/example/index.js – expected
    • path in browser /example/ – not expected

The URL re-write behaviour is pretty common within Gatsby, for example:

www.example.com/a-page will re-write to www.example.com/a-page/ – and in nearly all cases other than the example/index.js I want it to happen.

Typescript: type is object where property names are unknown

I am currently making a component in React and one of the properties is called ‘initNavData’. This is an object where the property names will always be different names and there are an unknown amount of these properties. Each of them will have the same structure though. How can I create a type for this?

I saw the [x: string] suggestion, but will this allow for an unlimited amount of properties?

interface WizardProps {
  id: string;
  // parentWizard: string
  isSubwizard: boolean;
  wizardName: string;
  initNavData: {
    [x: string]: {
      label: string;
      status: string;
      current: boolean;
      active: boolean;
      icon: string;
      key: string;
    }
  }
}

Error: TypeError: Failed to execute ‘fetch’ on ‘Window’: Invalid name. What could be the issue here?

I am getting a type error:

Error: TypeError: Failed to execute 'fetch' on 'Window': Invalid name
at HTMLFormElement.loginDataHandler (index.js:77:9)

I have searched google for hours now and tried all the suggested solutions but noe seem to be working on my end.

Kindly I am stack, can’t make any progress.

function loginDataHandler(e) {
  e.preventDefault();
  loginObject = {
    email: emailInput.value,
    passwordInput: passwordInput.value
  };
  console.log(loginObject);
  const newLocal = "https://mawingu.cbaloop.com/cba/api/v1/access/login";
  fetch(newLocal, {
      method: 'POST',
      body: JSON.stringify(loginObject),
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        'Access-Contr"ol-Allow-Origin': 'http://localhost:5500',
        " Access-Control-Allow-Methods ": "POST",
        ' Authorization ': ` None  `,
        "Access-Control-Allow-Headers": "X-Requested-With",
        'referrerPolicy': 'no-referrer'
      },
    })
    .then(
      res => res.json()
    )
    .then(
      data => console.log(data)
    )
    .catch((error) => {
      console.log('Error:', error);
    });
}

what could be the issue? Kindly help..