Uncaught RangeError: Maximum call stack size exceeded when I open my sideBar

I am using a package @reactour/[email protected] for producing a tour for my website for both desktop and mobile screen.

My query is for mobile screen.

When user is touring my web on mobile than at a specific step I need to open the sideBar ( currently sideBar is opening and working perfect ) but when the sideBar opens it shows error messages in the console.

Here I am updating the state for opening the sidebar

` useEffect(() => {
    if (isMobile) {
      if (props.customeState === 3)
        setTimeout(() => {
          setMobileOpen(true);
        }, 250);
      else setMobileOpen(false);
      //if (props.customeState === -1) TourStartPopupOpenM();
    }
  }, [props.customeState]);`

input range slider with custom steps as an array – react js

I want to set an array as steps in range slider

here is my code:

    import { useState } from 'react';
import { Slider } from 'antd';

const App = () => {

  const [ rangeValue, setRangeValue ] = useState([120, 233, 364, 3645, 45634, 23563, 49888, 22334, 16472]);
  
  return (
    <>
      <Slider  min={50} max={50000} step={rangeValue} />
    </>
  );
};

Obtain total formik error count within a fieldarray

Given the following Yup validation setup which has a nested Formik FieldArray:

  parentLevel: Yup.array().of(
    Yup.object({
      childrenLevel: Yup.array().of(
        Yup.object({
          childName: Yup.string().required('Name is required'),
          childAge: Yup.number().required('Age is required')
        })
      )
    })
  )

I need to calculate the total formik errors found within the childrenLevel fieldarray.

For example, assuming the user presses a “Add Children” button twice for FieldArray childrenLevel and enters no information for both Child Name and Age for those two records, I would like to obtain the error count from formik of 2 errors.

Unsure how to approach this using errors.parentLevel to determine total errors within childrenLevel.

“Cannot read property ‘connect’ of undefined

I am getting an error on pg.connect not defined. In the Handler module.


I am trying to create a table using postgres in fastify. I have and handle routes folder that handles the routes and sends API requests. When I hit the http://localhost:3000/initDB route the error says

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "Cannot read property 'connect' of undefined"
}

this is my Table module, looks like Table module is not getting fastify instance how can i solve this issue.

const fastify = require("../server");

const Table = async (req, reply) => {
  await fastify.pg.connect(onConnect);
  function onConnect(err, client, release) {
    if (err) return reply.send(err);
    client.query(
      'CREATE TABLE IF NOT EXISTS "users" ("id" SERIAL PRIMARY KEY,"name" varchar(30),"lastname" varchar(30));',
      function onResult(err, result) {
        release();
        reply.send(err || result);
      }
    );
  }
};

module.exports = {
  Table,
};

Routes file,

I have handled routes here,

//const fastify = require("fastify");
const { Table } = require("./Handler/CreateTable");
const { GetUsers, PostUsers } = require("./Handler/Handler");
const CreateTable = {
  handler: Table,
};
const getUsers = {
  handler: GetUsers,
};

const postUsers = {
  handler: PostUsers,
};

async function routes(fastify, options) {
  fastify.get("/initDB", Table);
  fastify.get("/users", getUsers);
  fastify.post("/users/create", postUsers);
}

module.exports = routes;

server.js file,

const fastify = require("fastify")({ logger: true });
fastify.register(require("fastify-postgres"), {
  connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_SERVICE}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DB}`,
});

module.exports = fastify;
fastify.register(require("./routes"));

// Run the server
const start = () => {
  fastify.listen(3000, "0.0.0.0", (err, address) => {
    if (err) {
      fastify.log.error(err);
      process.exit(1);
    }
  });
};
start();

enter image description here
This is error, please tell me how can I solve this error.

pg connect error to be solved

type here

I want, using my private API, to fetch my data but I want them to be checkboxes

Here’s what I have so far

main.html (it’s a form btw)

 <div class="form-group form-check-inline">
     <input class="form-check-input" type="radio" name="region" id="US" value="US">
     <label class="form-check-label" for="US">US</label>
</div>

api.js

document.addEventListener('DOMContentLoaded', () => {
const urlUS = new URL("http://127.0.0.1:3000/api/v1/regionApi/regionProduct/1")
document.getElementById('US').addEventListener('click', getRegionUS)

function getRegionUS() {
        fetch(urlUS, {
            method:'GET'
        })
            .then(res => res.json())
            .then(data => {
                data.forEach(function(product){
                    output = `
                    <div class="form-group form-check">
                    <input class="form-check-input" type="checkbox" value="${product.productname}" id="${product.id}">
                    <label class="form-check-label" for="${product.id}">
                    ${product.productname}
                    </label>
                    </div>
                    `
                })
                
                document.getElementById('US').innerHTML = output
                console.log(data)
            })
            .catch(error => console.log('error'))
    }

})

When clicking on the radio button I do get the information I am looking for in my api. What am I missing ? Why wouldn’t it appear in checkboxes ? What should I try ?

While rendering a component it is showing an error- “Cannot update a component (`App`) while rendering a different component (`EventList`). “

I Can’t render my events. Its showing this error –
“Cannot update a component (App) while rendering a different component (EventList). To locate the bad setState() call inside EventList, follow the stack trace as described in https://reactjs.org/link/setstate-in-render”

Here is EventList Component code –

import { useEffect, useState } from "react";
import EventList from "../../event-list";
import EventForm from "../event-form";

const EventAction = ({
    getEventsByClockID,
    addEvent,
    updateEvent,
    clockID,
    deleteEvent,
    deleteEventsByClockID,
}) => {
    const [isCreate, setIsCreate] = useState(false);
    const [isToggle, setIsToggle] = useState(false);
    const [eventState, setEventState] = useState(null)

    const handleCreate = () => {
        setIsCreate(!isCreate);
    }
    
    useEffect(() => {
        setEventState(getEventsByClockID(clockID, true));
    }, [isToggle])

    const handleToggle = () => {
        setIsToggle(!isToggle);
    }

    return (
        <div>
            <div>
                <button onClick={handleCreate}>Create Event</button>
                <button onClick={handleToggle}>Toggle Events</button>
            </div>
            {isCreate && (
                <>
                    <h3>Create Event</h3>
                    <EventForm
                        clockID={clockID}
                        handleEvent={addEvent}
                    />
                </>
            )}
            {isToggle && (
                <>
                    <h3>Events of this clock</h3>
                    <EventList 
                        clockID={clockID}
                        eventState={eventState}
                        deleteEvent={deleteEvent}
                        updateEvent={updateEvent}
                        deleteEventsByClockID={deleteEventsByClockID}
                    />
                </>
            )}
        </div>
    )
}

export default EventAction;

Here is my App Component Code –

import ClockList from "./components/clock-list";
import LocalClock from "./components/local-clock";
import useApp from "./hooks/useApp";
import { localClockInitState } from "./initialStates/clockInitState";

const App = () => {

  const {
    localClock,
    clocks,
    updateLocalClock,
    createClock,
    updateClock,
    deleteClock,
    getEventsByClockID,
    addEvent,
    deleteEvent,
    updateEvent,
    deleteEventsByClockID,
  } = useApp(localClockInitState);

  return (
    <div>
      <LocalClock 
        clock={localClock} 
        updateClock={updateLocalClock} 
        createClock={createClock} 
      />
      <ClockList 
        clocks={clocks}
        localClock={localClock.date}
        updateClock={updateClock} 
        deleteClock={deleteClock}
        getEventsByClockID={getEventsByClockID}
        addEvent={addEvent}
        deleteEvent={deleteEvent}
        updateEvent={updateEvent}
        deleteEventsByClockID={deleteEventsByClockID} 
      />
    </div>
  )
}

export default App;

and Here is my useApp hook –

import { useState } from "react";
import deepClone from "../utils/deepClone";
import generateID from "../utils/generateId";
import useEvents from "./useEvents";

const getID = generateID('clock');

const useApp = (initValue) => {
  const [localClock, setLocalClock] = useState(deepClone(initValue));
  const [clocks, setClocks] = useState([]);

  const {
    // events,
    // getEvents,
    getEventsByClockID,
    addEvent,
    deleteEvent,
    deleteEventsByClockID,
    updateEvent,
  } = useEvents();

  const updateLocalClock = (data) => {
    setLocalClock({
      ...localClock,
      ...data,
    })
  }

  const createClock = (clock) => {
    clock.id = getID.next().value;
    
    setClocks((prev) => ([
      ...prev, clock
    ]))
  }

  const updateClock = (updatedClock) => {
    setClocks(clocks.map(clock => {
      if(clock.id === updatedClock.id) return updatedClock;

      return clock;
    }));
  }

  const deleteClock = (id) => {
    setClocks(clocks.filter(clock => clock.id !== id));
  }

  return {
    localClock,
    clocks,
    updateLocalClock,
    createClock,
    updateClock,
    deleteClock,
    getEventsByClockID,
    addEvent,
    deleteEvent,
    updateEvent,
    deleteEventsByClockID,
  }
}

export default useApp;

I want to show all events incorporated with each individual clock.

Select not changing value after jQuery load event

Within my below example, I’ve a little select and a button. When I change the select value to e.g., 5 and press the button to reload the HTML select, I am wondering now why the displayed value inside the select is not reset after the jQuery load event, even if I set selected="selected" inside my HTML code?

(function($) {
  $(document).ready(function() {
    $('button').click(function() {
      let select = $('#select');

      console.log(`Value before: ${select.val()}`);

      $('#wrapper').load(location.href + " #wrapper", function() {
        let select = $('#select');

        console.log(`Value after: ${select.val()}`);
      });
    });
  });
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
  <select id="select" name="quantity">
    <option value="1">1</option>
    <option value="2" selected="selected">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
  </select>
</div>
<button>Load</button>

Shopping cart using JSON and JavaScript [closed]

I would like to create simple shopping cart with JavaScript, and JSON files, similar to AliExpress. After fetching the data from a JSON file on my computer, to the main box, how can I add all elements from the main box to the cart (container buyCart).

This functionality should be added after clicking the button. I would like to do it the simplest way possible. Could you give some advice or projects example how to do it?

[.js] (https://i.stack.imgur.com/LtXm0.jpg),

[.json] (https://i.stack.imgur.com/Hy31x.jpg)

How to return value from a javascript call in Jupyterlab?

I am struggling to read clipboard from jupyterlab.
My jupyter server is running on a remote instance using docker, so pyperclip and other similar tricks are not working. The idea is to use javascript but I have very limited experience using it. I am able to get the clipboard value and paste it to the log console but not to get back the value to python.

The usual trick using ipython.notebook.kernel.execute is not working.

See below the working example. Note that this has to be run in Chrome as afaik Firefox is blocking this feature.

Any suggestion is more than welcome ๐Ÿ™‚

Patrick

my_js = """
async function paste(input) {
  const text = await navigator.clipboard.readText();
  return text
}

paste().then((value) => console.log(value));
"""

import ipywidgets as widgets
from IPython.display import HTML, Javascript
button = widgets.Button(
    description='Button',
    disabled=False,
    button_style='',
    tooltip='Button',
    icon='check'
)
        
output = widgets.Output()

@output.capture(clear_output=False)
def on_button_clicked(b):
    
    display(Javascript(my_js))

button.on_click(on_button_clicked)
display(button, output)

# if you don't want to use ipywidgets, this would also work :
get_ipython().run_cell_magic("javascript", "",my_js)

Act when element exists, but don’t fail when it doesn’t (Cypress E2E tests)

I’m writing E2E tests in Cypress (version 12.3.0). I have a page with a table in a multi-step creation process that requires some data from back-end application. In some cases (rarely, but it occurs) the request gets stuck and the loader never disappears. The solution is simple: go back to the previous step and return to the “stuck” table. The request is sent anew and most likely receives a response – the process and the tests can proceed further. If the loader is not present, then going back and forth should be skipped (most of the times).

I managed to work around that with the code below, but I’m wondering if it could be done with some built-in Cypress functions and without explicit waiting. Unfortunately, I didn’t find anything in the Cypress docs and on StackOverflow. I thought that maybe I could use the then function to work on a “conditionally present” element, but it fails on get, that’s why I’ve used find on the jQuery ancestor element.

  waitForBuildingData() {
    return cy.get('.data-table')
             .should('exist')
             .then(table => {
               if (this.loaderNotPresent(table)) {
                 return;
               }
               cy.wait(200)
                 .then(() => {
                   if (this.loaderNotPresent(table)) {
                     return;
                   }
                   cy.get('button')
                     .contains('Back')
                     .click()
                     .get('button')
                     .contains('Next')
                     .click()
                     .then(() => this.waitForBuildingData());
                 });
             });
  }

  loaderNotPresent(table: JQuery) {
    return !table.find('.loader')?.length;
  }

Why is the PUT request indefinitely pending in this Angular form?

I am working on a form in Angular 14. Because of how the API is made, I am using a PUT request to add form data. I run into a problem while doing that.

In form.component.ts I have:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { FormService } from '../services/form.service';

@Component({
  selector: 'my-app',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css'],
})
export class FormComponent {
  public accountTypes!: any;
  public selectedAccountType: any;

  public form: FormGroup = new FormGroup({
    first_name: new FormControl('', Validators.required),
    last_name: new FormControl('', Validators.required),
    email: new FormControl('', [Validators.required, Validators.email]),
    accountInfo: new FormGroup({
      account_type: new FormControl(''),
    }),
  });

  constructor(private formService: FormService) {}

  ngOnInit(): void {
    this.getAccountTypes();
  }

  public getAccountTypes() {
    this.formService.getAccountTypes().subscribe((response) => {
      this.accountTypes = response;
      this.form.controls['accountInfo'].patchValue({
        account_type: this.accountTypes[0].value
      });
    });
  }

  public sendFormData() {
    console.log(this.form);
    this.formService.sendFormData(this.form.value).subscribe((response) => {
      console.log(response);
    });
  }
}

In the component’s template:

<form [formGroup]="form">
  <div class="form-grid">
    <mat-form-field appearance="outline" floatLabel="never">
      <mat-label class="mat-label">Fast name:</mat-label>
      <input class="mat-input" matInput formControlName="first_name" />
    </mat-form-field>

    <mat-form-field appearance="outline" floatLabel="always">
      <mat-label class="mat-label">Last name:</mat-label>
      <input class="mat-input" matInput formControlName="last_name" />
    </mat-form-field>

    <mat-form-field appearance="outline" floatLabel="never">
      <mat-label class="mat-label">Email:</mat-label>
      <input class="mat-input" matInput formControlName="email" />
    </mat-form-field>

    <div formGroupName="accountInfo">
      <mat-radio-group
        formControlName="account_type"
      >
        <mat-radio-button
          *ngFor="let accountType of accountTypes"
          [value]="accountType.value"
        >
          <span class="top-label">{{ accountType.label }}</span>
        </mat-radio-button>
      </mat-radio-group>
    </div>
  </div>
  <div class="center">
    <button
      (click)="sendFormData()"
      mat-raised-button
      color="primary"
      [disabled]="!form.valid"
    >
      Submit
    </button>
  </div>
</form>

In form.service.ts I have:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormData } from '../models/Form.data';

@Injectable({
  providedIn: 'root',
})
export class FormService {
  httpOptions: object = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    }),
  };

  apiURL: string = 'https://637e1e5d9c2635df8f9993a9.mockapi.io';

  constructor(private http: HttpClient) {}

  public getAccountTypes(): Observable<any> {
    return this.http.get<any>(`${this.apiURL}/accountType`);
  }

  public sendFormData(formData: FormData): Observable<FormData> {
    return this.http.put<FormData>(
      `${this.apiURL}/addFormData`,
      formData,
      this.httpOptions
    );
  }
}

The problem

At for submission, the request is indefinitely pending.

How can I fix this problem?

Fetch Amazon product details by link. How?

I am trying to fetch Amazon product details (product name, image, price, etc.) to my website.

but I can’t do that

This is my code:

let header = new Headers({
        "User-Agent": "My User-Agent",
});

fetch("url", {
    method: 'GET',
    withCredentials: true,
    crossorigin: true,
    mode: 'no-cors',
    headers: header,
}).then((res) => {
    return res.text();
}).then((result) => {
    document.write(result);
}).catch((err) => {
    console.log(err);
});

Please help me ……..

enter image description here
I get nothing, but i need the whole html of that amazon page.

React Native Expo: read/write external files

I wanted to know if/how it’s possible to read/write non-app files with Expo. I specifically need to access files that fall outside of the app’s directory, such as the downloads folder, images folder, and any other external folder. Expo docs on FileSystem say that it is only able to access app files, and not external files.

What is immutability in Redux Toolkit and how to implement it?

I know Immer library translates all mutable code to immutable one in createSlice() in Redux Toolkit , but I still want to write immutable reducers. Is this code immutable? If not how to correct it? What is immutability in Redux Toolkit and how to implement it?

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Tab } from '../../logic/types'
import { TabsState, updateTabPayload } from '../types'

const initialState: TabsState = {
  tabs: []
}

export const tabsSlice = createSlice({
  name: 'tabs',
  initialState,
  reducers: {
    loadTabs: (state, tabs: PayloadAction<Tab[]>) => {
      state.tabs = [...state.tabs, ...tabs.payload]
    },
    createTab: (state, tab: PayloadAction<Tab>) => {
      state.tabs = [...state.tabs, tab.payload]
    },
    updateTab: (state, data: PayloadAction<updateTabPayload>) => {
      const index = state.tabs.findIndex((tab) => tab.id === data.payload.id)
      state.tabs[index] = { ...state.tabs[index], ...data.payload.update }
    },
    deleteTab: (state, id: PayloadAction<number>) => {
      state.tabs = state.tabs.filter((tab) => tab.id !== id.payload)
    }
  }
})

export const { loadTabs, createTab, updateTab, deleteTab } = tabsSlice.actions

export default tabsSlice.reducer

I have tried to find information about this but still don’t get it.