React Native – Same Function call in child component but different result

maybe this question has been asked before, but unfortunately I was unable to find the answer.

I have got a screen called AccountManagement, where I can change the users data and in the end there is a button which updates the data.

const AccountManagement = (props) => {
    const {userData} = useContext(AuthContext)
    const [name, setName] = useState(userData.name)
    //other data...
    const update = () => {
        userData.name = name
        // set other data
        updateProfile(userData)
        navigation.navigate('Profile')
    }
}

So far, so good everything works fine. But if I call the same function (update()) in an other component via props, the changed state of name for example is ignored. Below, there is the return call of the same screen AccountManagement

 return(
    <SafeAreaView style={styles.container}>
        <HeaderBar updateInfo={update}/>
        <TextInput 
            style={styles.input}
            value={name}
            onChangeText={setName}
            placeholder=""/>
    <TouchableOpacity style={styles.changeContainer} 
                      onPress={update}>
        <Text style={styles.change}>Update Info</Text>
    </TouchableOpacity>
)

In the component HeaderBar, I have got a TouchableOpacity, which should do the exact thing as the TouchableOpacity in AccountManagement, call update(), which it does, but the changed name is never used when I press the TouchableOpacity in the HeaderBar component

const HeaderBar = (props) => {
  return(
    <View>
        <TouchableOpacity onPress={props.updateInfo} style={styles.rightContainer}>
            <Text style={styles.rightText}>Update Info</Text>
        </TouchableOpacity>
    </View>
  }
)

Even if I try to print with console.log I cannot see the change.

My question now is:

Why is the changed name ignored, when I press update from the HeaderBar component?

How can I fix this issue?

Thank you in advance

How to filter data when saved in local state?

I have an array of sections every section has an options array,
and have a maximum of options selected,

Let say

Section ‘Drinks’ has a max option 1

So I can just select one option from this section.

Section ‘Potatoes’ has a max option 2

Here I can check two options from this section.

So I have an array of sections and his options object,
Like this:

{
    idOfExtra: 44
    maximum_options: 1
    minimum_options: 1
    name: "drinks"
    radioData: [
        {
         calories: null,
         id: 245,
         maximum: 100,
         name: "Miranda orange",
         price: "0.00",
         price_unit: "USD",
        },
        {…}, {…} // other options
    ], 
}

So the issue is I want to set those options in an array named selectedOptionsQty to send to a backend, but before this, I want to check if I reached the max of Section or not And maximum option itself.

So The unique thing I can check about it is the idOfExtra ‘section id’ and compare it with the idOfExtra in the options object.

What I tried.
check if the currently selected option exists before in the checkbox array – that’s for style things “fill bg” -.

if the item is not selected before I push it to the two arrays (quantity, checkbox).
but before that, I check if the selected item has the same section id And the total quantity == maximum I show an alert for max reached options for this section.

otherwise, I push it to the arrays (quantity, checkbox).

But I got an unexpected behavior. Here’s Screen Record of current behavior.

Here’s a live example – Full Code

Hud animation in a certain pattern, with CSS and HTML

I am trying to make a certain Hud pattern inside my game using CSS and HTML.
I already have it like this picture.

So I am trying to put it like this picture (Photoshop edit)

I tried many things doing this, one thing i had it but then it stays like it when for example the Heart one dissapears, what needs to be happen is if the heart one dissapears the shield one will take it’s place, such as the others will move on the other locations. My last edit made it only fixed, it removed the heart btu the others stays on its place.

Hopefully someone can send me on the right direction.

The current code of the first picture:

HTML:

        <div class="hud-status">
            <div class="hud-circle hud-voice"><i id="VoiceIcon" class="fas fa-microphone"></i></div>
            <div class="hud-circle hud-health"><i class="fas fa-heart" style="color: #1fb0b4;"></i></div>
            <div class="hud-circle hud-armor"><i class="fas fa-shield-alt" style="color: #1f47b4;"></i></div>
            <div class="hud-circle hud-hunger"><i class="fas fa-hamburger" style="color: #b44e1f;"></i></div>
            <div class="hud-circle hud-thirst"><i class="fas fa-glass-whiskey" style="color: #008cff;"></i></div>
            <div class="hud-circle hud-stress"><i class="fas fa-brain" style="color: #ff0000;"></i></div>
            <div class="hud-circle hud-air"><i class="fas fa-lungs" style="color: #0083a3;"></i></div>
            <div class="hud-circle hud-nos"><i class="fas fa-meteor" style="color: #b41f51;"></i></div>
            <div class="hud-circle hud-timer"><i class="fas fa-hourglass-half" style="color: #6200ff;"></i></div>
        </div>

CSS:

    .hud-status {
        display: flex;
        position: absolute;
        display: none;
        left: 1.5vh;
        bottom: -4vh;
    }

    .hud-circle > i {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%) rotate(-45deg);
        color: white;
        font-size: 1.9vh;
    }

    .car-speed-circle {
        position: absolute;
        bottom: 5vh;
        left: 30vh;
        width: 8vh !important;
        height: 8vh !important;
        border-radius: 50%;
    }

    .hud-circle {
        transform: rotate(45deg);
        position: relative;
        width: 4vh !important;
        height: 4vh !important;
        margin: 0.3vh 1vh;
        float: left;
        box-shadow: 1px 1px 5px rgb(0, 0, 0);
    }

After implementing Apple Signin I am getting error ‘requestedOperation’ must be a value of AppleAuthRequestOperation in react native

I am trying to implement Apple Authentication in react native app. But I am getting error saying Error: RNAppleAuth.AppleAuthRequestOptions 'requestedOperation' must be a value of AppleAuthRequestOperation.

I have implemented it in the same way as given in this guide https://github.com/invertase/react-native-apple-authentication

Still, I am getting this error and I am not able the solution for this.

My code:

import { appleAuth } from "@invertase/react-native-apple-authentication";

import Axios from "axios";

export default function AppleSignButton(props) {
  /**
   * CallBack function for the button.
   */
  const onAppleButtonPress = async () => {
    // Make a request to apple.
    const appleAuthRequestResponse = await appleAuth.performRequest({
      requestedOperation: appleAuth.Operation.LOGIN.LOGIN,
      requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
    });

    // Get the credential for the user.
    const credentialState = await appleAuth.getCredentialStateForUser(
      appleAuthRequestResponse.user
    );

    // If the Auth is authorized, we call our API and pass the authorization code.
    if (credentialState === appleAuth.State.AUTHORIZED) {
      console.log(appleAuthRequestResponse.authorizationCode);

      Axios.post("https://test****/api/apple", {
        token: appleAuthRequestResponse.authorizationCode,
      }).then((res) => {
        if (res?.data?.user) {
          Alert.alert(
            "Number of connections: " + res.data.user.nbOfConnections.toString()
          );
        }
      });
    }
  };



I need to implement Apple signup & sign-in methods in react native app. How can I make this work?

How to write unit test for dynamic form array in Angular 8

I am new in Unit test writing.

I am trying to write unit test for below two function, but i am not able to make it green.

validateBatchSize($event, index: number) {
    const value = $event.value;
    if (value !== '' && value === 'Continues') {
      const formControl = this.items.at(index).get('batchSize');
      formControl.setValidators([Validators.required]);
      formControl.updateValueAndValidity();
    } else {
      const formControl = this.items.at(index).get('batchSize');
      formControl.clearValidators();
      formControl.updateValueAndValidity();
    }
  }

patchForm() {
    this.makeLineForm.patchValue({
      clusterId: this.data.clusterId,
      clusterName: this.data.clusterName,
      country: this.data.country,
      factoryName: this.data.factoryName,
      factoryId: this.data.factoryId,
      bigCategory: this.data.bigCategory,
    });
    if (this.data.title === 'Edit') {
      this.makeLineForm.patchValue({
        makeLineName: this.data.makeLineName,
        sapWCCode: this.data.sapWCCode,
        makeVendor: this.data.makeVendor
      })
      this.items.clear();
      for (const item of this.data.plist) {
        item.lineId = item.lineId.split(',');
        item.subfamilyId = item.subfamilyId.split(',');
        this.addItem(this.createItem(item));

      }
    }
  }

createItem(data = null) {
    const formgrp = this.fb.group({
      productType: ['', Validators.required],
      processTechType: ['', Validators.required],
      subfamilyId: ['', Validators.required],
      lineId: ['', Validators.required],
      batchSize: ['']
    });
    if (data) {
      formgrp.patchValue(data);
    }
    return formgrp;
  }
  addItem(item) {
    this.items.push(item);
  }

I have tried below Unit test but it is throwing error.

For patch form i am getting below error..
TypeError: this.data.plist is not iterable

But for validation function i am getting below error for get controls.
TypeError: Cannot read properties of undefined (reading ‘get’)

it('should Call Patch Form', () => { 
     component.data = [{
      lineName: '1',
      lineId: 2,
      subfamilyId: 3,
      plist: [
        { lineId: ['P1','P2'], subfamilyId: ['SP - VFFS'] }
      ]
    }
    ];
    component.data.title = 'Edit';
    const sp1 = spyOn(component, 'addItem');
    fixture.detectChanges();
    component.patchForm();
    fixture.detectChanges();
    expect(component.addItem).toBeTruthy();  
  });

  it('should call validateBatchSize', () => {    
    const data = 'Continues';
    const index = 1;
    component.makeLineForm.get('batchSize');
    component.validateBatchSize(data,index);
    expect(component.validateBatchSize).toBeTruthy();
  });

Can anyone please help me to fix this error and help to write proper unit test for below 2 function

React – Create Error Checking for Props in Components

Let’s say I’m creating a component and I want the value of a prop I’m passing to be an integer which is less than 10. What I want is if the prop is either not an integer or is greater or equal to 10 for an error to occur in React.

Example of how I want this to work:

export default function Component (props){
    typeof(props.number) != 'number' && // raise exception
    props.number >= 10 && // raise exception
}

Currently having an issue with my If else function in JavaScript. The if statement works but the else statement does not [closed]

Hi so this is a very basic issue that I’m currently not able to solve. Using only JavaScript I’m trying to create a like button that changes it text content from an empty heart to a full heart while also having an increment and decrement functionality. I am using unicode as the text content.

My issue is that the if statement seems to be working just fine since on a click it does go from an empty heart to a full heart while also incrementing, but the else statement doesn’t seem to be. It just seems to be stuck in the full heart and only keeps incrementing on click.

I’ve tried using else if as well but it doesn’t seem to work either.

Any advice is appreciated.

let likes = Math.floor(Math.random() * 100)+1;
const likesDiv = document.createElement("span");
const likesButton = document.createElement("button");
likesDiv.appendChild(likesButton);

const emptyHeart = 'u2661';
const fullHeart = 'u2665';
likesButton.textContent = emptyHeart;
likesDiv.innerText = `${likes}`;

likesButton.addEventListener("click", toggle)
    
    function toggle() {
      if (likesButton.textContent = emptyHeart) {
        likesButton.textContent = fullHeart
        likes++;
        likesDiv.innerText = `${likes} `;
      }
      else{
        likesButton.textContent = emptyHeart;
        likes--;
        likesDiv.innerText = `${likes} `;
      }
    };

Can I programatically define a class with private fields and methods without eval?

The MDN docs for private fields mention:

It is a syntax error to refer to # names from out of scope. It is also a syntax error to refer to private fields that were not declared before they were called, or to attempt to remove declared fields with delete.

Outside of private fields, I can define a function which returns a constructor which can then be invoked as a class:

function CtorCreator(...) {
   const CtorBeingCreated = function Whatever(...) {...}
   // programmatically manipulate CtorBeingCreated
   return CtorBeingCreated
}

const Ctor = CtorCreator(...)
const instance = new Ctor();

In this I can programmatically define fields and methods based on arguments passed to the CtorCreator function. For example

...
   CtorBeingCreated.prototype[...] = ...
...

Can I also define private fields and methods that way? E.g. some way to allow me to do

   ...
   addPrivateFieldToCtor(CtorBeingCreated, <field-name>, <initial-value>)
   // or 
   addPrivateMethodToCtor(CtorBeingCreated, <method-name>, <method-body>) // method body can access <field-name> previously defined  
   ...

onPress event is not working with custom button in my React Native code?

I’m working on a React Native project as a beginner. I’m creating a custom button called “RoundedButton” using touchableOpacity. But after creating this button when I use this and try to trigger an event using onPress like <RoundedButton onPress = {some function}/> it does not work.
Here is my code:

my RoundedButton.js code:

import React from 'react';
import {TouchableOpacity, Text, StyleSheet} from 'react-native';
import {colors} from '../utils/colors';

export const RoundedButton = ({
  style = {},
  textStyle = {},
  size = 125,
  ...props
}) => {
  return (
    <TouchableOpacity style ={[styles(size).radius, style]}>
      <Text style = {[styles(size).text, textStyle]}>{props.title}</Text>
    </TouchableOpacity>
  )

};

my Timer.js code where I uses the above custom button:

import React, {useState} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {colors} from '../../utils/colors';
import {fontSizes, spacing} from '../../utils/sizes'
import {Countdown} from '../../components/Countdown';
import {RoundedButton} from '../../components/RoundedButton';

export const Timer = ({focusSubject}) => {
  const [isStarted, setIsStarted] = useState("false");
  const onPress = () => setIsStarted("true");
  
  return (
    <View style={styles.container}>
      <View style={styles.countdown}>
        <Countdown isPaused={!isStarted}/>
      </View>      
      <View>
        <Text style={styles.title}>Focusing on: </Text>
        <Text style={styles.task}>{focusSubject}</Text>
      </View>    
      <RoundedButton title="Start" size={50} onPress={onPress}/> 
      <Text style={{color: 'white'}}>{isStarted ? "True" : "False"}</Text>
    </View>    
  )
};

I have not included styles code to make it simpler to find the issue. I want to know the correct method to use onPress functionality in React Native. Please help as soon as possible. No error is shown, App is working but the pressing event is not working, so I am not able to find out the actual issue.

print multiple copies in php using window.print

I am trying to print multiple copies of just a product name on a sticker. No of copies would be passed by popup onto print.php page.
I tried using while loop to use window.print but it prints only 1 copy.
heres my code:

function PrintPage() {
     var count = <?echo $prnt?>;
while (count >0){
       // alert("print");
    window.print();
    count--;
    
}
 window.close();

}
document.loaded = function(){
    
}
window.addEventListener('DOMContentLoaded', (event) => {
    PrintPage()
    setTimeout(function(){ window.close() },750)
});

used alert to debug if loops works, its showing.
I know this is regularly asked question ,however, I tried and its not working for me. Please help

React framer-motion – how to start counting scrollYProgress starting from specific div

What I want to do is to count the scrollYProgress when the viewport arrives the top of the container and scrollYProgress should be 1 when leaving the box. How can I do it?

The current problem is that scrollYProgress start counting at the top of the application.

enter image description here

App.js

import React, { useState, useEffect } from "react";
import "./styles.css";
import { motion, useViewportScroll } from "framer-motion";

export default function App() {
  const { scrollYProgress } = useViewportScroll();

  useEffect(() => {
    return scrollYProgress.onChange((v) => {
      console.log(v);
    });
  }, [scrollYProgress]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <motion.div>
        <div
          style={{ height: "500px", margin: "1rem", border: "1px solid grey" }}
        >
          How to start Counting the percentage from 0 here
        </div>
      </motion.div>
      <h2>The percentage will be 100% when arriving the end of the box</h2>
    </div>
  );
}

Codesandbox
https://codesandbox.io/s/adoring-poincare-curjo?file=/src/App.js:177-192

As I import BrowserRouter from ‘react-router-dom’ my app stops working. I have attached the error. The error in index.js file but I haven’t touched i

×
TypeError: Object(…) is not a function
./node_modules/react-router/index.js
C:/devansh/React/routing-on-http–01-starting-setup/http–05-finished/node_modules/react-router/index.js:56
53 | */
54 |
55 |

56 | const NavigationContext = /#PURE/createContext(null);
57 |
58 | if (process.env.NODE_ENV !== “production”) {
59 | NavigationContext.displayName = “Navigation”;
View compiled

Descending order is not working in Datatable when coming from database

From the database I am fetching the value :-

Array
(
    [0] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2022-01-10
            [candidate_name] => sathish sat
        )

    [1] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2022-01-10
            [candidate_name] => sathish sat
        )

    [2] => stdClass Object
        (
            [company_email] => [email protected], [email protected]
            [schedule_date] => 2022-01-05
            [candidate_name] => sathish sat
        )

    [3] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Sai Surendra Datar
        )

    [4] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Rahul Raj
        )

    [5] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Dilpreet kaur
        )

    [6] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Sai Surendra Datar
        )

    [7] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Rahul Raj
        )

    [8] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-21
            [candidate_name] => Rahul Raj
        )

    [9] => stdClass Object
        (
            [company_email] => [email protected], [email protected]
            [schedule_date] => 2021-12-18
            [candidate_name] => Sai Surendra Datar
        )

    [10] => stdClass Object
        (
            [company_email] => [email protected], [email protected]
            [schedule_date] => 2021-12-18
            [candidate_name] => sathish sat
        )

    [11] => stdClass Object
        (
            [company_email] => [email protected]
            [schedule_date] => 2021-12-18
            [candidate_name] => sathish sat
        )

)

But when showing in the datatable order are missmatching refer the image URL I have mentioned
Display of the datatable
URl – https://i.stack.imgur.com/FJLgg.png
enter image description here

This is my code:-

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap4.min.css" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap4.min.js"></script>
<table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>Candidate Name</th>
                <th>Company Email</th>
                <th>Schedule Date</th>
            </tr>
        </thead>
        <tbody>
            <?php $x = 1; foreach ($candidate_list as $record) { ?>
                            <tr> 
                                <td style="text-align: left;color: #5e5e5e;"><?php echo $record->candidate_name; ?></td>
                                <td style="text-align: left;color: #5e5e5e;"><?php echo $record->company_email; ?></td> 
                                <td class="sorting sorting_asc sorting_1" style="text-align: left;color: #5e5e5e;"><?php echo date('d-m-Y', strtotime($record->schedule_date)); ?></td>
                                </td>
                            </tr>
                        <?php $x++;} ?>
        </tbody>
       
    </table>
    <script type="text/javascript">
        $(document).ready(function() {
    $('#example').DataTable();
} );
    </script>

Kindly give me the solution. I need the order as from the database. How to solve this?

ReactJS Prop returning default value in some functions

I have a ReactJS file where at the top I have one of my props defined as

const [items, setItems] = useState(0);

This updates a value I show on the screen properly, and when I read the value of items in some functions, I do get the proper value of items. However, on one specific function with the prototype of const updateCart = (client) => {}, when I try to get the value of items, I get the default value defined in the useState(0);. I do understand that props do not always update instantly, but even after reading the value correctly in another function, when I try to read it in the updateCart() function I always get the default value, not the current value. How can I read the current value in my updateCart() function?

Thank you

Set value in object at dynamic key, possibly further than first given scope

I have 2 user-provided strings acting as a key, and a value. Let’s say, for example, "foo" and "Hello World!". I have an object that I want to modify, and set obj.foo to Hello World!.

The problem is that the key can lead to an indefinitely nested object. For example, I should be able to use the key foo.bar[baz].qux or any strange JS-syntax sequence like that to set a value inside a nested object, or declare one if necessary.

Furthermore, I’m gonna have to access these values with another user-provided string that could be in a different format (for example, foo[bar][baz][qux] instead). Is there a way to do all of this without using eval()?

Before someone marks it, this question isn’t a duplicate of change structure of an object javascript because

  1. That question does not address the last part of this one,
  2. It’s 7 years old, and interacting with objects has become a lot easier over updates (maybe my question would be easier to answer with recent versions?) and
  3. It also doesn’t address using [] (not as big of a problem, until you have people using both types in one long expression)