TypeError: Cannot read property ‘type’ of undefined, js engine: hermes

I’m doing a questionnaire with a checkbox using formik, when marking an answer I get the following error: “ERROR TypeError: Cannot read property ‘type’ of undefined, js engine: hermes”

import React, { useState, useEffect } from "react";
import { View, Text, Button, Switch } from "react-native";
import { Formik, Field } from "formik";
import * as yup from "yup";
import AsyncStorage from "@react-native-async-storage/async-storage";
import "react-native-gesture-handler";

const schema = yup.object().shape({
  tetravalente: yup.boolean(),
  pneumococica: yup.boolean(),
  hepatiteB: yup.boolean(),
  febreAmarela: yup.boolean(),
  hpv4: yup.boolean(),
  vacinaVSR: yup.boolean(),
  vacinaDuplaBacteriana: yup.boolean(),
});

const QuestionarioScreen = ({ navigation }) => {
  const [respostasQuestionario, setRespostasQuestionario] = useState(null);

  const initialValues = {
    tetravalente: false,
    pneumococica: false,
    hepatiteB: false,
    febreAmarela: false,
    hpv4: false,
    vacinaVSR: false,
    vacinaDuplaBacteriana: false,
  };

  const handleSubmit = async (values) => {
    try {
      // Salvando as respostas do questionário no AsyncStorage
      await AsyncStorage.setItem(
        "respostasQuestionario",
        JSON.stringify(values)
      );
      console.log("Respostas do questionário salvas com sucesso:", values);

      // Aqui você pode navegar para a próxima tela ou fazer qualquer outra coisa que desejar
      navigation.navigate("PróximaTela");
    } catch (error) {
      console.error("Erro ao salvar as respostas do questionário:", error);
    }
  };

  useEffect(() => {
    // Recuperar as respostas do questionário do AsyncStorage
    const getRespostasQuestionario = async () => {
      try {
        const respostas = await AsyncStorage.getItem("respostasQuestionario");
        if (respostas !== null) {
          setRespostasQuestionario(JSON.parse(respostas));
        }
      } catch (error) {
        console.error("Erro ao recuperar as respostas do questionário:", error);
      }
    };

    getRespostasQuestionario();
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>Questionário de Vacina</Text>
      <Formik
        initialValues={initialValues}
        validationSchema={schema}
        onSubmit={handleSubmit}
      >
        {({ handleSubmit }) => (
          <View>
            <Field name="tetravalente" component={CheckBox} />
            <Field name="pneumococica" component={CheckBox} />
            <Field name="hepatiteB" component={CheckBox} />
            <Field name="febreAmarela" component={CheckBox} />
            <Field name="hpv4" component={CheckBox} />
            <Field name="vacinaVSR" component={CheckBox} />
            <Field name="vacinaDuplaBacteriana" component={CheckBox} />
            <Button title="Enviar" onPress={handleSubmit} />
          </View>
        )}
      </Formik>
    </View>
  );
};

const CheckBox = ({ field }) => (
  <View style={{ flexDirection: "row", alignItems: "center" }}>
    <Text>{field.name}</Text>
    <Switch
      value={field.value}
      onValueChange={(newValue) => field.onChange(field.name)(newValue)}
    />
  </View>
);

export default QuestionarioScreen;

I’m using an Android reulator in a React Native – Expo application. I’m trying to mark the answers without making an error.

Is there a way to access a nested array property with space in b/w?

I created this nested Array as practice work. In the second object of the nestedArr(which is the first in array understanding), I used space in between the property name ‘items list’ to store the data. I have tried to access data from the items lists array but, I keep having problem. can someone please help out with a hint.


const nestedArr =[
  {
    description: "Items",
    names: [
      "Pen",
      "Papers",
      "ink",
      "books"
    ]
  },
  {
    type: "Material",
    "items list": [
      "block",
      "water",
      "irons",
      "cements"
    ]
  }
];

const check = nestedArr[0].names[0]; //pen
const check2 nestedArr[1].["items list"][0]; // block
//Second Example

const nestAarray =[
 {
type: "Home Office",
detail: [
   "Location",
   "Address",
   "Postal Code",
   "Tel#"
},
{
practice: "Make Perfect",
failure: [
   "Lesson",
   "Teacher",
   "Master",
   "Print",
   "Success"
]
}
];

const check3 = nestArray[1].failure[2]; // Master
const check4 = nestArray[0].detail[0]; // Location

/* I have practice more and more with the second example. It's not a problem for me */

const nestedArr =[
{
description: “Items”,
names: [
“Pen”,
“Papers”,
“ink”,
“books”
]
},
{
type: “Material”,
“items list”: [
“block”,
“water”,
“irons”,
“cements”
]
}
];

const check = nestedArr[0].names[0]; //pen
const check2 nestedArr[1].[“items list”][0]; // block

SweetAlert2 Disappearing when Triggered from Pressing Return

I am using a document.onkeydown to fire when Return is pressed while an element is active and it fires this successfully:

$(#selid).trigger('singletap');

I’m using jQuery Touch Events to handle interactions.

I’m using this version of Sweet Alert2: https://rahulbhut21.github.io/SweetAlert2/

I can see my handler firing and see the console.log ok:

$('#selid').on('singletap', function(e) {
  console.log('Inside Singletap');
  e.preventDefault();
  swal('Test').catch(swal.noop);
  return false;  
});

When I click on #selid, the SweetAlert 2 alert shows fine, but when using the keyboard Return, it flashes and then disappears. I’ve tried to implement suggestions mentioned elsewhere, but the alert is still disappearing.

Bottom Navigation disappears when scrolling down, reappears when scrolling up?

Like the title says, I am trying to make my bottom navigation disappear when scrolling down, and reappear when scrolling up.

I tried following a tutorial about a top navigation, and thought I could mimic the results, and I tried to mimic an answer on here. Neither worked, it is not moving at all. Any help with this would be greatly appreciated, but I am VERY new to this, so feel free to explain it like I’m 5.

This was the code I tried:

html

<footer id="footer"><h1>Bottom of page<h1></footer>

css

footer {
     position: fixed;
     bottom: 0;
     width: 100%;
     height: 55px;
     margin: auto;
     align-items: center;
}

script

{
            var(prevScrollpos) = window.pageYOffset; 
            window.onscroll = function() {
                var currentScrollPos = window.pageYOffset;
                if (prevScrollpos > currentScrollPos) {
                    document.getElementById("footer").style.bottom = "-55px";
                } else {
                    document.getElementById("footer").style.bottom = "0";
                }
                prevScrollpos = currentScrollPos;
            }
        }

react pagination how to return to page 0 when chagne the category

when i change the category the pagination stell in the same page number and the other category page turn to blank page i want when change the category the page go to 0.

this is the spring boot api for display all the posts by category

    @GetMapping("/public/posts/category")
    public ResponseEntity<PageResponse<PostResponse>> getAllPostsByCategory(
            @RequestParam(name = "category", required = false) String categoryName,
            @RequestParam(name = "page", defaultValue = "0", required = false) int page,
            @RequestParam(name = "size", defaultValue = "10", required = false) int size
    ) {
        return new ResponseEntity<>(service.getAllPostsByCategory(page, size, categoryName), HttpStatus.OK);
    }

and this is the react route for the category page

<Route path="/category/:category" element={<CategoryPage />} />

How can I track the parameter change? and when it chagne set the page to 0

  const { category } = useParams();

  useEffect(() => {
    getPostsByCategory(category, pages, size).then((data) => {
      setContent(data.content);
      setTotalPages(data.totalPages);
    });
  }, [category, pages, size]);

  console.log(totalPages);

  return (
    <div className="h-[80vh] flex flex-col space-y-4 items-center justify-between">
      <div>
        {content.map((post) => (
          <Post key={post.id} post={post} />
        ))}
      </div>
      <Pageination pages={pages} setPages={setPages} totalPages={totalPages} />
    </div>
  );

Refresh Infinite Loop happening when trying to request in access token in a React Web App

I’m only a couple months in of learning front end development. I wrote a module to:

Make a GET fetch quest for an access token with the Spotify API

Parse the resulting authorization url for the access token and expiration time and set it to localstorage in the browser.

I know Implicit Grant Flow isn’t recommended for security reasons, but this is just a little portfolio project not intended for mass use.

I’m running into an issue where instead of loading Spotify’s authorization page right off the bat, it goes straight to the redirect_uri and then the url blinks rapidly which I think means there is some sort of refresh loop that keeps happening. I’ve searched over the Spotify documentation, chat GPT etc…and I can’t figure it out.

import React, { useEffect } from 'react';

const generateRandomString = (length) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};

const SpotifyAccessToken = ({ stateLength }) => {
  useEffect(() => {
    const clientId = '';
    const redirectUri = 'http://localhost:5173/';
    const scope = 'playlist-modify-private playlist-modify-public user-read-private';
    const responseType = 'token';
    const state = generateRandomString(stateLength)

    const queryParams = new URLSearchParams({
      client_id: clientId,
      redirect_uri: redirectUri,
      scope: scope,
      response_type: responseType,
      state: state,
    });

    const authorizeUrl = `https://accounts.spotify.com/authorize?${queryParams}`;

    // Redirect the user to the authorize URL
    window.location.href = authorizeUrl;
  }, []);

  useEffect(() => {
    const queryParams = new URLSearchParams(window.location.search);
    const error = queryParams.get('error');

    if (error) {
      console.error('Authorization error:', error);
      
      return;
    }

    const accessToken = queryParams.get('access_token');
    const expiresIn = parseInt(queryParams.get('expires_in'));
    const expirationTime = new Date().getTime() + expiresIn * 1000;

    localStorage.setItem('spotifyAccessToken', accessToken);
    localStorage.setItem('spotifyTokenExpirationTime', expirationTime);

    if (expirationTime < Date.now()) {
      // Token has expired, redirect to the initial authorization URL
      const clientId = 'd90891e3a05449b5992d7c531d9a8cc1';
      const redirectUri = 'http://localhost:5173/';
      const scope = 'playlist-modify-private playlist-modify-public user-read-private';
      const responseType = 'token';
      const state = generateRandomString(stateLength)

      const queryParams = new URLSearchParams({
        client_id: clientId,
        redirect_uri: redirectUri,
        scope: scope,
        response_type: responseType,
        state: state,
      });

      const authorizeUrl = `https://accounts.spotify.com/authorize?${queryParams}`;

      window.location.href = authorizeUrl;
    } else {
      // Clear parameters from the URL to avoid potential issues
      window.history.replaceState({}, document.title, window.location.pathname);
    }
  }, []);

  return (
    <div>
      <p>Redirecting to Spotify for access...</p>
    </div>
  );
};

export default SpotifyAccessToken;

What ever s Git hub [closed]

I have started programming recently and I don’t have any clear understanding in github.so,when i open or log in that I usually don’t understand the terms and usage of that. So can anyone of explain github to me? I will be grateful.

I have visited on github and tried to understand github several times but I am facing difficulties and also I don’t have any experience before

Why does my data URL not fetch and exicute the JavaScript?

I want to have a data url that fetches code from my two github repos, just like this one (not mine, but working)

data:text/html, <script src='https://cdn.jsdelivr.net/gh/dragon731012/caudns/jszip.js' defer></script> <script src='https://cdn.jsdelivr.net/gh/dragon731012/caudns/filesaver.js' defer></script> <script src='https://caudns.vercel.app/main.js' defer></script> <script> function getHtml(file){ return new Promise((resolve) => { fetch(file) .then((response) => response.text()) .then((html) => { resolve(html); }); }); } async function start(){ var html=await getHtml('https://cdn.jsdelivr.net/gh/dragon731012/caudns/data.txt'); html=html.toString(); console.log(html); document.body.innerHTML=html; } start(); </script>

however, i want mine to fetch from this https://raw.githubusercontent.com/dinguschan-owo/dingusproxy/main/script.js and this https://raw.githubusercontent.com/dinguschan-owo/dingusproxy/main/index.html. the html works, but not the js.

i tried changing the js to https://cdn.jsdelivr.net/gh/dinguschan-owo/dingusproxy/main/script.js, and that didn’t help either

problem with install nvm in Mac air 2015 13

I’m having some problems with the installation on a Mac Air 2015 13″. I downloaded Brew, but it didn’t resolve the issue for me. Does anyone have an idea how to fix it?

I need it to deploy a new feature in a web app

I downloaded Brew, but it didn’t resolve the issue. I don’t know what could have happened.

Problem with slider value sending it to php

I have this slider:

<form id="sliderForm1" action="registerValidation.php" method="POST">
  <label for="sliderValue1">Kiek su tuo sutinkate?:</label>
  <output id="sliderOutput1" name="sliderOutput1">0</output>
  <input type="range" min="0" max="100" value="0" id="sliderValue1" name="sliderValue1">
</form>

I have some javascript file, for checking lines, but its not essential here, there are no modification of values.

I try putting it to database:

$password_hash = password_hash($_POST["password"], PASSWORD_DEFAULT);


$mysqli = require __DIR__ . "/databaseConnect.php";


$sql = "INSERT INTO user (username, email, password_hash, slider1Value) VALUES (?, ?, ?, ?)"; //////////////!!!!!!!!!!!!!!!!!!!/////////////////////

try 
{
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("sssi", $_POST["username"], $_POST["email"], $password_hash, $_POST["sliderValue1"]); //////////////////////////////////////////////
    $stmt->execute();
    header("Location: login.php");
    exit;
} 
catch (mysqli_sql_exception $exception) 
{
    if ($mysqli->errno === 1062) //dublicate key element error number
    {
        die("El. pašto adresas arba vartotojo vardas jau užimtas");
    } 
    else 
    {
        die("Klaida: " . $exception->getMessage());
    }
}

DB view:
Db view

But I keep getting an error: Column ‘slider1Value’ cannot be null.
I tried to change value manually, tried to give output values to $stmt.

Error when submitting dependent select components with ShadCN/react-hook-form. How to use custom change functions

I want to create two Select components using ShadCN. I want these selects to have a dependency between each other.

This means that after a value is selected for categories, then the select of subcategories is populated with the filtered data accordingly.

This step is working fine.

However, when I click on submit the form, it is as if the category was an empty value and I believe it is because I am using a custom handle function in the onValueChange event instead of using the field.onChange.

I still haven’t gotten the hang of using the Form components and all its intricacies so I don’t understand how I can use my own change function to handle the events or even how I could have these components as reusable components and avoid DRY.

#... imports

export const TransactionForm = () => {
  const [selectedCategory, setSelectedCategory] = useState<string>("");
  const [selectedSubcategory, setSelectedSubcategory] = useState<string>("");
  const [filteredSubcategories, setFilteredSubcategories] = useState<string[]>(
    []
  );

  const form = useForm<z.infer<typeof TransactionSchema>>({
    resolver: zodResolver(TransactionSchema),
    defaultValues: {
      category: "",
      subcategory: "",
    },
  });

  const categories = [...dummyData.categories].map((item) => item.name);

  const onSubmit = (values: z.infer<typeof TransactionSchema>) => {
    console.log(values);
  };

  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category);
    setSelectedSubcategory("");
    console.log(category);
    const categoryData = dummyData.categories.find(
      (item) => item.name === category
    );
    if (categoryData) {
      setFilteredSubcategories(categoryData.subcategories);
    } else {
      setFilteredSubcategories([]);
    }
  };

  const handleSubcategoryChange = (subcategory: string) => {
    setSelectedSubcategory(subcategory);
  };

  return (

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          <div className="space-y-4">
            <FormField
              control={form.control}
              name="category"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Category:</FormLabel>
                  <Select
                    onValueChange={(value) => handleCategoryChange(value)}
                    defaultValue={field.value}
                  >
                    <FormControl>
                      <SelectTrigger className="w-[180px] h-[40px]">
                        <SelectValue placeholder="Category" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent className="bg-white">
                      <SelectGroup>
                        <SelectLabel>Category</SelectLabel>
                        {categories.map((option, index) => (
                          <SelectItem key={index} value={option}>
                            {option}
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="subcategory"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Subcategory:</FormLabel>
                  <Select
                    onValueChange={field.onChange}
                    defaultValue={field.value}
                    {...field}
                  >
                    <FormControl>
                      <SelectTrigger className="w-[180px] h-[40px]">
                        <SelectValue placeholder="Subcategory" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent className="bg-white">
                      <SelectGroup>
                        <SelectLabel>Subcategory</SelectLabel>
                        {filteredSubcategories.map((option, index) => (
                          <SelectItem key={index} value={option}>
                            {option}
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </FormItem>
              )}
            />
          </div>
          <Button type="submit" className="w-full">
            Save
          </Button>
        </form>
      </Form>
    </CardWrapper>
  );
};

How is this JS code related to Euler Number

function PayyaInterest(amount, interest) {
  interest = interest * amount / 100;
  return "$" + (interest + amount);
}

//annual interest
let annualInterest = PayyaInterest(45, 100);


//6 months interest
let monthlyInterest = PayyaInterest(45, 50);

//another 6 month
let combinedInterest = monthlyInterest * 2;

console.log(annualInterest !== combinedInterest)

what is Euler Number

how is the above code related to Euler Number you

Ay online recommendation to learn Euler Number using JavaScript

python web_page fuction returns invalid syntax

I am writing a simple webserver on a esp32 to control some leds.

def web_page(color_hex, brightness):
html = """
<!DOCTYPE html>
<html>
<head>
    <title>LED Control</title>
    <script>
    function updateColor(color) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/color", true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('color=' + encodeURIComponent(color));
    }

    function updateBrightness(brightness) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/brightness", true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('brightness=' + encodeURIComponent(brightness));
    }
    </script>
</head>
<body>
    <h1>LED Control</h1>
    <input type="color" onchange="updateColor(this.value)">
    <input type="range" min="0" max="255" step="1" onchange="updateBrightness(this.value)">
</body>
</html>
"""
    return html

this is the function in micropython and it return a invalid syntax on return html. And i can’t find the problem.

as soon as i delete the part between script, it works again (doesn’t return a error). also the old funtion worked fine:

def web_page(color_hex, brightness):
    html = f"""<!DOCTYPE html>
<html>
<head><title>LED Control</title></head>
<body>
    <h1>LED Control</h1>
    <form action="/color" method="post">
        <input type="color" name="color" value="{color_hex}">
        <input type="submit" value="Set Color">
    </form>
    <br>
    <form action="/brightness" method="post">
        <input type="range" name="brightness" min="0" max="255" step="1" value="{brightness}">
        <input type="submit" value="Set Brightness">
    </form>
</body>
</html>"""
    return html

i am also not the brightest in java, so it might be really obvious.

How can I configure prettier to stop turning “>” into “& gt;”?

My work situation does not allow the use of some characters such as “>”, “<“, or “&”. Instead, we use the html entity equivalent in the JavaScript.

Prettier keeps adding a space between my the characters in my HTML entity. How can I configure it to stop doing that?

Thanks!

I tried setting: htmlWhitespaceSensitivity to both ‘ignore’, and to ‘strict’. Neither of those options worked.

How can I prevent unauthorized access to my API endpoint?

Let me explain what I want to achieve and what I have tried.

//The Problem
I have an API endpoint built with nextjs
API Url Remote: – http://codingsamadhan.com/api/portfolio
API Url Local – http://localhost:3000/api/portfolio
this is the API for the portfolio items that I want to display on my website, and I did it. but the problem is anyone can request the API, even you can also request the endpoint.

// what I want?
Now this endpoint is publicly accessible, anyone can make GET request, I want to prevent this, I want only my website codingsamadhan.com should make the request, and only those who visit my website can see the portfolio items on my website without login or any session, I don’t want to allow anyone else to call my API endpoint in another place.

// I am thinking
I don’t want to authenticate the API URL using next-auth or JWT because I want to display the items on my website without login just like products, if there is any way to authenticate the endpoint using next-auth or JWT without login please let me know, I don’t know that.

// I have tried
I have tried api-key headers during API calls using the fetch() method, but I realize that the api-key is visible in the network tab of the browser console. so I feel the api-key headers are also meaningless if my api-key is visible to the public.

app/api/portfolio/route.js

export const GET = async (request) => {
  // get api key
  const headersList = headers();
  const apiKey = headersList.get("X-Api-Key");
  const validKey = process.env.API_KEY;

  // check valid api key
  if (validKey === apiKey) {
    await connectDB();
    const portfolioItems = await getPortfolioItems(request); // this function is created in another palce
    return NextResponse.json(portfolioItems);
  } else {
    return NextResponse.json({ message: "Unauthorized Access!" });
  }
};

fetch the api with headers

export const fetchPortfolioItems = async (category, siteName, sort, page) => {
  const response = await fetch(
    `/api/portfolio?siteCategory=${category || ""}&&siteName=${siteName || ""}&&sort=${sort || "latest"}&&page=${page || "1"}&&perPage=${3}`,
    {
      method: "GET",
      headers: {
        "X-Api-Key": "30JmsSQENLRPnpECk25gftymnKUQ9H1SMpQ5k4leFUTw0QgAA8vvH0gkzBV1heEXA7Wv9HK2WspLLPFn8BnSfaBd5xSZLgtk",
      },
    }
  );
  return response.json();
};

the “X-Api-Key” is visible in the network tab in the browser’s console, so this method is useless for me. enter image description here