Does setter function change in React’s useState [duplicate]

Defining a state in a React functional component, such as

const [state, setState] = useState();

does setState (the setter function) ever change? I could not find this specified in the documentation, and it is likely not specified and its behavior might change; but does anyone know how it currently works in React? (v16, v18).

While the question may seem irrelevant it may be interesting to know the answer. For example let us say I use some initializer code later in the component, which subscribes to window messages:

useEffect(() => {
  const messageListener = () => {
    // Parse the message, and if we decide to, change the state
    ...
    setState(...); // modify component state
  }
  // Subscribe to window messages
  window.addEventListener('message', messageListener, false);

  return () => { // Cleanup, 'destructor' code
    window.removeEventListener('message', messageListener, false);
  }
}, [setState])

As this initializer/destructor code needs to mutate the state, it uses setState. Then, the useEffect hook must depend on the setter setState‘s value (the function). As it is running non-trivial code (create and removing event listeners) that should be executed only once (at least once in my app’s lifetime) one would not want to re-run it often, which will happen if React decides to change setState.

So, is there a concrete specification on how useState creates and passes back the setter function? I imagine it is perfectly possible to have it never mutate (ie. always be the same function object) but it have not find its definition, and might depend on React’s version as well.

How to solve react native ‘undefined is not a function’ problem?

I was building an app using react-native and ‘react-native-push-notification’.

But an error occurred.
This is error message.

WARN:Possible Unhandled Promise Rejection (id: 3):

And

TypeError: undefined is not a function (near ‘…_reactNativePushNotification.default.localNotificationScedule…’)

I looked for various solutions regarding undefined is not a function, but couldn’t find one that worked for me.

This is my code.

LocalNotification.js

import {AppState, PushNotificationIOS} from 'react-native';
import PushNotification from 'react-native-push-notification';

const _handleAppStateChange = nextAppState => {
    if (nextAppState == 'active') {
        _registerLocalNotification();
    }
};

const _registerLocalNotification = () => {
    PushNotification.setApplicationIconBadgeNumber(0);
    PushNotification.cancelAllLocalNotifications();

    const messages = [
        'Take a moment to write in your journal!',
        'Did you write today's diary?',
        'Let's keep a diary!',
    ];
    const message = messages[Math.floor(Math.random() * messages.length)];

    let nextHour = new Date();
    nextHour.setDate(nextHour.getDate() + 1);
    nextHour.setHours(nextHour.getHours() - 1);

    PushNotification.localNotificationScedule(
        {
            //android
            vibrae: true,
            vibration: 300,
            priority: 'hight',
            visibility: 'public',
            importance: 'hight',

            //ios
            message,
            playSound: false,
            number: 1,
            actions: '["OK"]',

            repeatType: 'minute',
            date: new Date(Date.now()),
        }
    );
};

export default {
    register: async () => {
        PushNotification.configure({
            onNotification: function(notification) {
                notification.finish(PushNotificationIOS.FetchResult.NoData);
            },
            popInitialNotification: true,
        });

        _registerLocalNotification();

        AppState.addEventListener('change', _handleAppStateChange => {
           if (_handleAppStateChange !== 'active') {
              return;
           }
           AppState.remove();
        });
    },
    unregister: () => {
        AppState.addEventListener('change', _handleAppStateChange => {
           if (_handleAppStateChange !== 'active') {
              return;
           }
           AppState.remove();
        });
    },
};

Do you know the solution that this problem?
then please help me.

Reproduce the background of an existing website in HTML, CSS, JS

I would like to reproduce the same background of the Kleos Space website (the color gradient and the shapes), but I don’t know how to reproduce this color gradient in HTML, CSS, JS.

Here is the link to the website: https://kleos.space/

I analyzed the website using the development tools integrated in web browsers but I did not understand how the background was made.

Thanks in advance 🙂

How to populate nested dynamic form inputs with the data in Yii 2

I am using Yii 2 and the dynamic form widget.

I have a situation where the user selects an ASC center from the drop-down list. All the students belonging to that particular ASC center is returned from the server and should be populated in all the nested dynamic form input field.

It correctly gets populated for the first row, but as the user adds new students and new times, the populated data gets cleared and every time the user needs to select the ASC center for the data to be populated in the newly added students rows.

The below image shows the students populated for the first student row on selecting the ASC center

enter image description here

Below is the image which shows the Student input field gets cleared when a user adds new student or adds new time and hence user always has to select ASC center to populate all the student’s input with the data.

enter image description here

Below is the function which returns the students for selected ASC

public function actionStudentLists($id)
    {
        $countstudents = Student::find()->where(['ASCId' => $id])->count();//Counts number of students

        $Students = Student::find()->where(['ASCId' => $id])->all(); // Execute students for ASCId

        if ($countstudents > 0) {

        echo "<option value>Select Students</option>";  

            foreach ($Students as $Student) {
        ob_start();

             echo "<option value='" . $Student->StudentId . "'>" . $Student->StudentName . "</option>";
            }
        } else {
            echo "<option> - </option>";
        }
    }

Below is the _form.php

<?php
use yiihelpersHtml;
use yiibootstrapActiveForm;
use yiijuiDatePicker;
use wbragancadynamicformDynamicFormWidget;
use appmodelsAscassignment;
use appmodelsAsccenter;
use kartiktimeTimePicker;
use yiihelpersArrayHelper;
use appmodelsStudent;
?>

<script>

$(function () {
$(".dynamicform_student").on("beforeInsert", function(e, item) {
   $.post("index.php?r=student/student-lists&id='.'"+$("select#ascteacherreport- 
                ascid").val(),function(data){
                         $(".i").html(data); 
                   });
              });
          });

$(function () {
$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
            $.post("index.php?r=student/student-lists&id=' . '"+$("select#ascteacherreport-
                  ascid").val(),function(data){  
                 $(".i").html(data);
            });
        });
     });
</script>

<div class="ascteacherreport-form">

<?php $form = ActiveForm::begin(['id' => 'dynamic-form',  'options' => ['class' => 'disable-submit-
  buttons'], ]);?>

<div class="panel panel-primary " >
 <div class="panel panel-heading"><font size="3"><b>Teacher Report</b></font></div>
  <div class="row">
   <div class="col-sm-4">

     <?= $form->field($model, 'ASCId')->dropDownList(ArrayHelper::map(Asccenter::find()- 
              >leftJoin('ascassignment','`ascassignment`.`ASCId`=`asccenter`.`ASCId`')- 
              >where(['ascassignment.UserId' => Yii::$app->user->identity->getonlyid()])-
              >all(),'ASCId','ASCName'), ['prompt' => 'Select ASC Center','class'=>'form-
              control ascid','onChange' => '

              $.post("index.php?r=student/student-lists&id=' . '"+$(this).val(),function(data){
                $(".i").each(function()
                {
                 $(".i").html(data); // Populate the StudentId field having the class .i with the data
                });
             });
          '
      ]) ?>
</div>
<div class="col-sm-4">

    <?= $form->field($model, 'DateofReport')->widget(DatePicker::classname(), [ //'language' => 'ru',
                    'dateFormat' => 'yyyy-MM-dd',
                    'options' => ['class' => 'form-control picker','readOnly'=>'readOnly'],
                    'clientOptions'=>['changeMonth'=>true,
                       'changeYear'=>true,
                       'readOnly'=>true
                      ]]) ?>
</div>
</div>
</div>

<div class="panel panel-primary">
<div class="panel-heading"><font size="3"><b>Time and Student Details</b></font></div>
    <?php DynamicFormWidget::begin([
        'widgetContainer' => 'dynamicform_wrapper',
        'widgetBody' => '.container-items',
        'widgetItem' => '.time-item',
        'limit' =>10,
        'min' => 1,
        'insertButton' => '.add-time',
        'deleteButton' => '.remove-time',
        'model' => $modelsTime[0],
        'formId' => 'dynamic-form',
        'formFields' => [
        'FromTime',
        'ToTime'
        ],
    ]); ?>
<table class="table table-bordered">
  <thead>
     <tr bgcolor='#B8B8B8'>
         <th style='border: 1px solid black;'></th>
            <th class ="text-center" style='border: 1px solid black;'>Time</th>
                <th class ="text-center" style='border: 1px solid black;'>Student Details</th>
                    <th class="text-center" style='border: 1px solid black;'>
                            <button type="button" class="add-time btn btn-success btn-xs"><span 
                              class="fa fa-plus"></span> Add Time</button>
                    </th>
                </tr>
  </thead>
  <tbody class="container-items">
      <?php foreach ($modelsTime as $indexTime => $modelTime): ?>
        <tr class="time-item">
          <td class="vcenter" style='border: 1px solid black;'>
                <?php
                // necessary for update action.
                if (! $modelTime->isNewRecord) {
                        echo Html::activeHiddenInput($modelTime, "[{$indexTime}]ASCReportDetailsId");
                }
                ?>
         </td>
         <td style='border: 1px solid black;width:15%'>
                 <?=  $form->field($modelTime, "[{$indexTime}]FromTime")->label(true)-
                             >widget(TimePicker::classname(),[
                               'pluginOptions' => [
                                    'readOnly' => true,
                                    'minuteStep' => 1,
                         ],
                    ])?><br>

                <?=$form->field($modelTime, "[{$indexTime}]ToTime")->label(true)-
                               >widget(TimePicker::classname(),[
                                'pluginOptions' => [
                                    'readOnly' => true,
                                    'minuteStep' => 1,
                        ],
                    ])?>
        </td>
        <td style='border: 1px solid black;'>
                <?= $this->render('_form-studentdata', [
                                     'form' => $form,
                                    'indexTime' => $indexTime,
                                    'modelsStudentdata' => $modelsStudentdata[$indexTime],
                               ]) ?>
        </td>
        <td class="text-center vcenter" style='border: 1px solid black;'>
            <button type="button" class="remove-time btn btn-danger btn-xs"><span class="fa fa-minus">
            </span></button>
        </td>
    </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<?php DynamicFormWidget::end(); ?>

</div>
    <div class="form-group">

         <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model-
                              >isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>
<?php ActiveForm::end(); ?>

</div>

Below is the nested inner form _form-studentdata.php

<?php

use yiihelpersHtml;
use yiihelpersArrayHelper;
use yiibootstrapActiveForm;
use yiiwebUploadedFile;
use wbragancadynamicformDynamicFormWidget;
use appmodelsStudent;
?>

<?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_student',
    'widgetBody' => '.container-student',
    'widgetItem' => '.student-item',
    'limit' => 50,
    'min' => 1,
    'insertButton' => '.add-student',
    'deleteButton' => '.remove-student',
    'model' => $modelsStudentdata[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'StudentId',
        'Subject',
        'Topic',
        'Confidence',
    ],
]); ?>
<table class="table table-bordered">
    <thead>
        <tr bgcolor='#B8B8B8'>
            <th style='border: 1px solid black;'></th>
                <th class ="text-center" style='border: 1px solid black;'>Student</th>
                <th class ="text-center" style='border: 1px solid black;'>Subject</th>
               <th class ="text-center" style='border: 1px solid black;'>Topic</th>
            <th class ="text-center" style='border: 1px solid black;'>Confidence</th>
            <th class="text-center" style='border: 1px solid black;'>
                <button type="button" class="add-student btn btn-success btn-xs"><span
                      class="glyphicon glyphicon-plus"></span> Add Student</button>
            </th>
        </tr>
    </thead>
    <tbody class="container-student">
    <?php foreach ($modelsStudentdata as $indexStudent => $modelStudentdata): ?>
        <tr class="student-item">
            <td class="vcenter" style='border: 1px solid black;'>
                <?php
                    // necessary for update action.
                    if (! $modelStudentdata->isNewRecord) {
                        echo Html::activeHiddenInput($modelStudentdata, "[{$indexTime}]
                                 [{$indexStudent}]ASCTeacherReportTimeDetailsId");
                    }
                ?>
    </td>
        <td style='border: 1px solid black; width:30%'>
                
             <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]StudentId")-
                 >label(false)->dropDownList(ArrayHelper::map(Student::find()-
                 >all(),'StudentId','StudentName'),['prompt' => 'Select 
                 Student','class'=>'form-control i']) ?   // class i assigned to StudentId field

       </td>
        <td style='border: 1px solid black; width:30%'>

            <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]Subject")-
                   >label(false)->textInput(['maxlength' => true]) ?>

       </td>
    <td style='border: 1px solid black; width:30%'>
        <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]Topic")->label(false)-
                               >textInput(['maxlength' => true]) ?>
    </td>

    <td style='border: 1px solid black; width:30%'>
                <?= $form->field($modelStudentdata, "[{$indexTime}][{$indexStudent}]Confidence")-
                                >label(false)->textInput(['maxlength' => true]) ?>
    </td>
     <td class="text-center vcenter" style=" border: 1px solid black;width: 90px;">
        <button type="button" class="remove-student btn btn-danger btn-xs"><span class="glyphicon 
              glyphicon-minus"></span>
        </button>
    </td>
  </tr>
  <?php endforeach; ?>
 </tbody>
</table>
<?php DynamicFormWidget::end(); ?>

Shadow and Highlight filter with ColorMatrix

I’m trying to create 2 separate filters (Shadow and Highlight) using ColorMatrix but couldn’t find any solution on the internet.

Here is the definition for Shadow and Highlight: Highlights are the lightest elements in an image, whereas shadows are the darkest areas.

I found how contrast works:

  • Increase amount : shadows darker and highlights brighter
  • Decrease amount : bring the shadows up and the highlights down
const v = (amount || 0) + 1;
const o = -0.5 * (v - 1);

const matrix: ColorMatrix = [
    v, 0, 0, 0, o,
    0, v, 0, 0, o,
    0, 0, v, 0, o,
    0, 0, 0, 1, 0,
];

Why is it hard for Javascript to work perfectly in a hosted sever than when it is on local host [closed]

Why is it hard for Javascript to work perfectly in a hosted sever than when it is on local host.
When it comes to Linking Javascript to html if you don’t watch closely before add it to your project it is much more difficult for you to debug. Like I mean putting it in between the <head> </head> and after the <body>. Why?.

And it slows down the performance of the websites and even some time it does not load some other files.

But still i always find the solution to it.
How can a developer know the right position for his/her js file…?

I tried it so many times never work, buy I still overcome it with my frontend skills.
I feel like i love node than just pure js, and also love working with frameworks or libraries.
love react cause it user friendly.

Making a scene static and a 3D element inside of scene rotating on drag

Frame and I am trying to make a 3D element where the background(scene) is always fixed, so I don’t have that 360deg viewport. I want that 3D element inside of scene to always be in the center of viewport and that it can rotate on drag for 360deg and always stays in the center of viewport

This is the code I have so far, but I can still drag around scene in 360deg and 3D element is not rotatable when dragged

<html>
  <head>
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
  </head>
  <body>
    <a-scene>
      <!-- Static Blue Background -->
      <a-sky color="#4CC3D9"></a-sky>
      
      <!-- Rotatable 3D Element -->
      <a-entity
        geometry="primitive: box"
        material="color: #FFC65D"
        position="0 1.5 -3"
        rotation="0 0 0"
        drag-rotate-component
      ></a-entity>
    </a-scene>
  </body>
</html>

Uncaught TypeError: Cannot read properties of undefined (reading ‘data’) at Category i am getting this error please help me to solve it

when i do not map any data in Category.jsx it works fine as soon as i try to grab data from strapi api and write following code in Category.jsx i got UncoughtTypeError in my consol.

Home.jsx

import { useEffect, useContext } from "react";

import "./Home.scss";

import Banner from './Banner/Banner'
import Category from "./Category/Category";
import Products from "../Products/Products";
import { fetchDataFromApi } from "../../utils/api";
import { Context } from "../../utils/context";

const Home = () => {
    const { categories, setCategories, products, setProducts } = useContext(Context);
    useEffect(() => {
        getProducts();
        getCategories();
    }, []);

    const getProducts = () => {
        fetchDataFromApi("/api/products?populate=*").then(res => {
            console.log(res)
            setProducts(res)
        });
    }

    const getCategories = () => {
        fetchDataFromApi("/api/categories?populate=*").then(res => {
            console.log(res)
            setCategories(res)
        });
    }

    return (
        <div>
            <Banner />
            <div className="main-content">
                <div className="layout">
                    <Category categories={categories} />
                    <Products products={products} headingText="Popular Products" />
                </div>
            </div>
        </div>
    );
};

export default Home;

Category.jsx

import "./Category.scss";

import cat1 from '../../../assets/category/cat1.jpg'

const Category = ({categories}) => {
    return (
        <div className="shop-by-category">
            <div className="categories">
                {categories.data.map((item) => {
                    <div key={item.id} className="category">
                        <img src={process.env.REACT_APP_STORE_URL + item.attributes.img.data.attributes.url} 
                        alt="" />
                    </div> 
                })}        
            </div>
        </div>
    );
};

export default Category;

context.jsx

import { createContext, useState } from "react";

export const Context = createContext();

const AppContext = ({ children }) => {
    const [categories, setCategories] = useState()
    const [products, setProducts] = useState()
    return (
        <Context.Provider
            value={{
                categories,
                setCategories,
                products,
                setProducts
            }}>
            {children}
        </Context.Provider>
    );
}

export default AppContext;

api.js

import axios from "axios";

const params = {
    headers: {
        Authorization: "bearer" + process.env.REACT_APP_STRIPE_APP_KEY
    }
}

export const fetchDataFromApi = async (url) => {
    try {
        const { data } = await axios.get(process.env.REACT_APP_STORE_URL + url, params)
        return data
    } catch (error) {
        console.log(error)
        return error
    }
}

As this is my first project i am not very comfortable with it, looking for easy and better solution

Problems executing useEffect in a React application

I’m building an application in React and I’m having some problems, I want to change some styles of a component that was created with Material UI, Paper, this style should be changed when TYPE_USER is equal to 0, for this I created two useEffect, one to receive and save the data, the other to do the verification and change the styles, this is the code

function SideBarLeft() {
  const style = useStyles();
  
  const [disableSearch, setDisableSearch] = useState(false);
  const [placeholder, setPlaceholder] = useState('Funcionário ou NIF');
  const [funcao, setFuncao] = useState('');
  const [nome, setNome] = useState('');

  useEffect(() => {
    const token = localStorage.getItem('token');
    const decoded = jwt_decode(token);
    const id = decoded.user.ID;
    console.log('id: ' + id)
    
    axios
        .get(`${API_BASE_URL}/user/${id}`) 
        .then((res) => {
          setFuncao(res.data.user.TIPO_UTILIZADOR);
          setNome(res.data.user.NOME_UTILIZADOR);
        
        })
        .catch((err) => {
          console.log(err);
        }
    );
  } , []);

  useEffect(() => {
    if ( funcao === 0  ) {
      console.log('funcao: ' + funcao)
      setDisableSearch(true);
      setPlaceholder(nome);
    } else {
      setDisableSearch(false);
      setPlaceholder('Funcionário ou NIF');
    }
  }, [ funcao, nome]);
  }, []);

This is the code from the Paper where I want to change the styles:

return (
  <div className={style.sideBarSearch}>
    <Paper component="form" className={disableSearch ? style.sideBarSearchPaperFuncionario : style.sideBarSearchPaper} >
      <InputBase
        className={style.sideBarSearchInput}
        sx={{ ml: 1, flex: 1, input: {
          color: 'white',
          "&::placeholder": {
            opacity: 1,
           },
         }, }}
         placeholder={placeholder}
         readOnly={disableSearch}
         inputProps={{ style: { color: disableSearch ? '#FFFFFF' : 'black' }}}
        />
        {disableSearch ? null : <SearchIcon sx={{ p: '10px', color: '#0093FF'}} />
        }
    </Paper>
  </div>

I’ve tried a few times, mainly with console.log to check if after the if ( funcao == 0 ), it was being executed, but no, even though the data was being set correctly

Why can’t typescript recognize the type of a parent through its child?

Let’s take a look at the next example:

type A_Number = {
    type:  'NUMBER'
    numberValue: number
}

type A_String = {
    type: 'STRING',
    stringValue: string
}

type B_Number = {
    a: A_Number;
    numberData: number;
}

type B_String = {
    a: A_String;
    stringData: string;
}

type A = A_Number | A_String
type B = B_Number | B_String

function test_A_NUMBER(a: A_Number) {}
function test_B_NUMBER(b: B_Number) {}

function test_B(b: B) {
    if (b.a.type === 'NUMBER') {
        test_A_NUMBER(b.a) // TS correctly recognizes that b.a is A_Number
        test_B_NUMBER(b)   // but it can't recognize that b is B_Number (I have typing error here :()
    }
}

Here is the working example of the code.

Does anybody know why typescript can’t recognize the specific type of the variable b? It looks like it has everything it needs to do it (it knows that b is B and it knows that b.a is A_Number).

leaflet-simple-map-screenshoter – print by click custom button

I have to use javaScript leaflet-simple-map-screenshoter, but this library by defaut add print button in the map containers. But I need to pin this method to my custom button. Unfortunately I don’t know how to do this by analyzing only one examples that I found (it show how to use this library with default button) or find some examples showing how to pin appropriate method to custom button. But I found demo, where it is done, so I know that this is possible.

Maybe someone did something like this?

Sort an Map with Maps inside

is there a way to sort a Map of Maps in JS?

function travelTime(array) {
    let countryOrdersMap = new Map()

    for (let commands of array) {
        let [country, townName, cost] = commands.split(" > ");
        cost = Number(cost);

        if (!countryOrdersMap.has(country)) {
            countryOrdersMap.set(country, new Map());
            countryOrdersMap.get(country).set(townName, cost)

        } else {
            let countryTown = countryOrdersMap.get(country)
            for (let test of countryTown) {
                let name = test.shift()
                let newCost = test.shift()
                if (name !== townName) {
                    countryOrdersMap.get(country).set(townName, cost)
                } else {
                    let finalCost = Math.min(cost, newCost)
                    countryOrdersMap.get(country).set(townName, finalCost)
                }
            }
        }

    }
    console.table(countryOrdersMap)
travelTime([
    "Bulgaria > Sofia > 1000",
    "Bulgaria > Sopot > 800",
    "France > Paris > 2000",
    "Albania > Tirana > 1000",
    "Bulgaria > Sofia > 1200"
])

I have to sort these by two criteria:

  1. by key alphabetically (Albania, Bulgaria , France )
  2. by values of the second map in descending order ( Sopot – 800, Sofia – 100)

Any help will be much appreciated. Thank you.

I’ve tried several different tactics with no success.

What are the Usecases of general face detection APIs

What are the examples Where exactly normal face detection API might be used ? Not the Full scan of face like in mobile devices But if we just use this for detecting face in the picture, like this API – General face detection API Screenshot

clarifai.com/openvino/face-detection/models/face-detection-0200

If I would be a junior web developer working in Service Based Software company , Can you please give some examples where i could have come across this face detection Component .

In which type of webApp we might be using this ?
Any healthcare related webApps (In which page/section?)
Do we use this in any User registration form or anywhere ?
Just want to know where this could be used ? General face detection API Screenshot

where this could be used