Why useContext doesn’t re-render the component – React.js + Laravel

I’m stucked… 🙂

I have a single view in Laravel where React appends to the specific ID. What I try to do is to open the pop-up after click the button using an useContext. Below is my code:

Globalcontext.js

import React from 'react';

export const initialState = {
    usersData: null,
    clickedNewUserButton: false,
    showAddUserPopup: false,
    isLoading: true,
};

export const GlobalContext = React.createContext(initialState);

UsersPageMain.js

import React, { useEffect, useContext } from 'react';
import ReactDOM from 'react-dom';
import { GlobalContext } from '../state/GlobalContext';
import FiltersButton from '../components/Users/FiltersButton';
import AddUserButton from '../components/Users/AddUserButton';
import UsersTable from '../components/Users/UsersTable';
import AddNewUserPopup from '../components/Users/AddNewUserPopup';

function UsersPageMain(){
    const initialState = useContext(GlobalContext);

    if(initialState.clickedNewUserButton){
        return (
            <GlobalContext.Provider value={initialState}>
                <div className='container users-list-page'>
                    <div className='row'>
                        <FiltersButton/>
                        <AddUserButton/>
                    </div>
                    <div className='row'>
                        <UsersTable></UsersTable>
                    </div>
                </div>
                <AddNewUserPopup/>
            </GlobalContext.Provider>
        )
    }else{
        return (
            <GlobalContext.Provider value={initialState}>
                <div className='container users-list-page'>
                    <div className='row'>
                        <FiltersButton/>
                        <AddUserButton/>
                    </div>
                    <div className='row'>
                        <UsersTable></UsersTable>
                    </div>
                </div>
            </GlobalContext.Provider>
        )
    }
}

export default UsersPageMain;

if (document.getElementById('user-list-page')) {
    ReactDOM.render(<UsersPageMain />, document.getElementById('user-list-page'));
}
UsersTable.js

import axios from 'axios';
import React, {useContext,useEffect,useState} from "react";
import { GlobalContext } from "../../state/GlobalContext";
import Preloader from '../Preloader';
import Conf from '../../conf/Conf';

export default function UsersTable(){
    const context = useContext(GlobalContext);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        axios.get('/api/get-all-users')
        .then(response => {
            context.usersData = response.data.data;
            setLoading(false);
        })
    })

    if(loading){
        return (
            <Preloader isLoading={loading}/>
        )
    }else{
        return (
            <>
                <Preloader isLoading={loading}/>
                <div className="col-12">
                    <div className="table-responsive rounded-table">
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Avatar</th>
                                    <th>Name</th>
                                    <th>Surname</th>
                                    <th>Group</th>
                                    <th>Email</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {context.usersData.map((user,index) => {
                                    return (
                                        <tr key={user.email}>
                                            <th>{user.id}</th>
                                            <th>
                                                <div className="avatar" style={{backgroundImage: `url(${Conf().assetPath}uploads/avatars/${user.avatar})`}}></div>
                                            </th>
                                            <th>{user.name}</th>
                                            <th>{user.surname}</th>
                                            <th>Group</th>
                                            <th>{user.email}</th>
                                            <th>
                                                <button type="button" className="btn theme-edit-btn"><i className="fa-solid fa-pencil"></i></button>
                                                <button type="button" className="btn theme-delete-btn"><i className="fa-solid fa-delete-left"></i></button>
                                            </th>
                                        </tr>
                                    )
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            </>
        )
    }
}
AddUserButton.js

import React, { useContext } from "react";
import { GlobalContext } from "../../state/GlobalContext";

export default function AddUserButton(){

    const context = useContext(GlobalContext);
    
    function triggerUserPopupClick(){
        context.clickedNewUserButton = true
    }
    
    return(
        <div className="col-xl-2 col-md-4 col-12">
            <button type="button" onClick={() => {triggerUserPopupClick()}} className="btn theme-primary-btn">Add New <i className="fa-solid fa-angles-right"></i></button>
        </div>
    )
}

The problem is exactly in the AddUserButton component where I’m trying to update global context to re-render main UsersPageMain component. I don’t have any idea what I’m doing wrong… If you could, please give some tips what I need to do to achieve opening popup after clicking this component.

Can you create a Typescript type that has exactly one of a set of properties AND is indexable by that set

I have the following types:

type OrBranch = {
   or: Node[]
}

type AndBranch = {
   and: Node[]
}

I’d like a type Branch that can be either an OrBranch or an AndBranch. So I first tried:

type Branch = AndBrand | OrBranch

Work great, unless I want to do something like:

let branch: Branch = ...
let andOr = 'and';   // or 'or'

let nodes = branch[andOr]

Then I get that branch isn’t indexable. OK, so I try an indexable type:

type AndOr = 'and' | 'or';
type Branch = Record<AndOr, Node[]>;

But that requires that BOTH and and or exist, so I can’t cast and AndBranch to Branch in this case.

Similarly

type Branch = Record<AndOr, Node[]> | AndBranch | OrBranch

doesn’t work, for the same reason.

I know there’s a way to require exactly one of and and or (like the answer to Enforce Typescript object has exactly one key from a set). But that type is not indexable.

Is it possible to get both effects?

How does AutoHotkey hot strings work? Is it detectable like copy/paste is?

Is there any way for a website to detect that I’m using AutoHotkey on Chrome instead of typing out the full thing? I used https://www.keyboardtester.com/ to test and it detects a backspace and all the letters typed out immediately as opposed to Ctrl+C which it detects as Ctrl+C only. I’m not sure how the site works but I’m guessing whatever javascript code runs in the background detects all the characters pressed. Would it be the same for any other website?

Also, sometimes the strings are missing a few characters like Hell World instead of Hello World. I thought if I knew how hot strings worked, I could fix it or at least find a workaround.

Node.js: callback is not a function (Google Cloud function)

I need a Google Cloud function that uses the Vision API (Safe Search) and gives back the results. This is my approach (I’m using the inline editor in the browser):

index.js:

exports.pruefeNSFW = async (req, res) => {
  let inp = req.query.storagefile;

  const vision = require('@google-cloud/vision');
  // Creates a client
  const client = new vision.ImageAnnotatorClient();

  // Performs safe search detection on the local file
  const [result] = await client.safeSearchDetection(inp);
  const detections = result.safeSearchAnnotation;

  console.log('Safe search:');
  console.log(`Adult: ${detections.adult}`);
  console.log(`Medical: ${detections.medical}`);
  console.log(`Spoof: ${detections.spoof}`);
  console.log(`Violence: ${detections.violence}`);
  console.log(`Racy: ${detections.racy}`);

  res.status(200).send(detections);
};

package.json:

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/vision": "2.4.2"
  }
}

Test Input:

{
"storagefile": "https://firebasestorage.googleapis.com/v0/b/xxx.xxx.com/o/xxxxxxxxx"
}

The function crashes with this message:

Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging Details: callback is not a function

The logs only give this: Function execution took 2528 ms, finished with status: 'crash'


I don’t understand why it crashes. How can I fix this?

React match by id and map to return in div

I am stuck with below, console.log shows correct but in web output there is no values shown. I would appreciate support

const ServicesDetails = [
  ["text1", "text2", "text3"],
  ["text5", "text6", "text7"],
  ["text8", "text9", "text10"]
];

const getServicesDetails = (prop) => {
  let length = ServicesDetails.length
  for (let i = 0; i <= length; i++) {
    if (parseInt(prop) === parseInt(i)) {
        ServicesDetails[i].map(
        (item, e) => {
          console.log(item, e)
          return <div key={e}>{item}</div>
        } 
      )
    }
  } 
}

angular class functions not working/available when service response is assigned to an array

I have a below class Invoice with some data and methods in it but when I assign REST API array response to my component class array I observe that angular Invoice class methods like addItem, removeItem are not available.

I’ve tried this angular class method not working when populated by service but did not work for me.

Have a look at the below code,

1. Invoice class (angular class)

import { Customer } from "./customer";
import { InvoiceItem } from "./invoice_item";
import { Item } from "./item";

export class Invoice {
    invoiceId?: number;
    invoiceNumber: number;
    
    customer: Customer;
    invoiceItem: InvoiceItem[] = [];

    constructor(customer?: Customer, invoiceNumber?: number) {
        this.customer = customer;
        this.invoiceNumber = invoiceNumber;
        this.invoiceItem.push({itemId: 0, quantity: 0, rate: 0}); // default invoice_item
    }

    addItem() {
        this.invoiceItem.push({itemId: 0, quantity: 0, rate: 0}); // default invoice_item
    }

    removeItem(item) {
        this.invoiceItem.splice(this.invoiceItem.indexOf(item), 1);
    }
    
}

2. Component Class(angular)

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subject, Subscription } from 'rxjs';
import { Customer } from 'src/app/model/customer';
import { Invoice } from 'src/app/model/invoice';
import { InvoiceService } from 'src/app/services/invoice.service';

@Component({
  selector: 'app-admin-invoices',
  templateUrl: './admin-invoices.component.html',
  styleUrls: ['./admin-invoices.component.css']
})
export class AdminInvoicesComponent {
  customerInvoices: Invoice[] = [];
  customerId: number; 

 
  constructor(private route: ActivatedRoute, 
              private invoiceService: InvoiceService) {
    this.customerId = (this.route.snapshot.paramMap.get('customerId'));

     this.invoiceService.getCustomerInvoices(this.customerId)
      .subscribe((invoices: Invoice[]) => {
        this.customerInvoices = invoices; // assigning service response
      });
  }

}

In the below image you can see service response. Also, we can see the **constructor** of type Object instead of type **Invoice** even if we have declared our customerInvoices array of type Invoice as customerInvoices: Invoice[] = []; in our component class.

service-response

Expected Output is as below:

expected-output

Silent saving image in electron.js

I have got problem with setting path to download files in this case for images. I download image from URL with blob construction like this:

async function downloadImage(imageSrc) {
    const image = await fetch(imageSrc)
    const imageBlog = await image.blob()
    const imageURL = URL.createObjectURL(imageBlog)

    const link = document.createElement('a')
    link.href = imageURL
    link.download = 'asd.png'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
} 

Then i catch a download signal on main.js like this:

session.defaultSession.on("will-download", (event, item, webContents) => {
        item.setSavePath( /local_dir/ + item.getFilename());
    }) 

When i log getFilename() i have got correct filename what i want, silent also too works because i havent got a window to locate directory of download, but when i look into directory it is empty.

Thanks for help.

When scrolling, stop at certain points

I need to scroll the image with background-position. To create a scrolling effect, I need to set scroll points, all this should happen in a specific block.

I need to create breakpoints, change breakpoints on scroll and assign it to a specific block. How to do it?

Run a script after location is changed, Javascript

I want to achieve something like this,
location.replace("some url"); alert("hello");

I know this won’t work but it runs before the next page is loaded and onload doesn’t seem to work either is there a way to achieve this ? Please just don’t tell there isn’t, although this isn’t a necessity it will be great if I can handle that in my project. THANK YOU

Difference between assigning function to props, with arrow function and without

I don’t understand what is the difference between assigning my handleButton method to the props with and without the arrow function. In React Developer Tools I see only this statement func: f func() {} and func2: f () {}, can you explain me the difference?

Code:

<MathButton
    operator="-"
    number={10}
    func={() => {
        this.handleButton;
    }}
    func2={this.handleButton}
></MathButton>

How can i do automictic Stop the Videos When Play Another Video in laravel site

I’m using YouTube iframe to embed videos on my site developed using php laravel framework. I want to ensure autometic stop others videos when i play one video. I am using following code but not workng it. Can anyone please help me!

<iframe id="youtube_player" class="yt_player_iframe" width="100%" height="350" 
 src="https://www.youtube.com/embed/{{$post->video_link}}" title="YouTube video player" 
 frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; 
 picture-in-picture" allowfullscreen></iframe>

 <script>
  $('.yt_player_iframe').each(function(){
  this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
  });
</script>

Multiply input range value by another number and display result

please how can i multiply the current input range value by 0.95 and display the result in a span tag when button is clicked?

<input id="aaj" type="range" min="{{amountmin}}" max="{{amountmax}}" step="0.003" value="{{amountmin}}">
<button id="aaw" class="aak" onclick="rig();">Range Slider Button</button>
<span class="result"></span>

three.js raycaster mouseover

I’ve been trying to set a “mouseover” effect that gives transparency to the box geometry only, but this applies also on the ground geometry and I’m not able to exclude the ground form this effect, any suggestions on how to achieve this?
I think I need to pass some arguments in intersectObject (scene.somenthing)

import * as THREE from '../../build/three.module.js';
import { OrbitControls } from '../../src/OrbitControls.js';

var controls;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const pointer = new THREE.Vector2(1,1);
const raycaster = new THREE.Raycaster();

const renderer = new THREE.WebGLRenderer({alpha:false,antialias:true});
renderer.setSize( window.innerWidth, window.innerHeight );

document.body.appendChild( renderer.domElement );

const light = new THREE.AmbientLight(0x303030);
const dLight = new THREE.DirectionalLight(0xffffff, 0.5);

light.add(dLight);
scene.add(light);

const geometry = new THREE.BoxGeometry(50,0.1,50);
const material = new THREE.MeshPhysicalMaterial( { color: 0x0fa8dc } );
const ground = new THREE.Mesh( geometry, material );

scene.add( ground );
camera.position.set(5,15,15);

controls = new OrbitControls(camera, renderer.domElement);
controls.maxPolarAngle = Math.PI / 2.1; 

//Raycaster reset materials
function resetMaterials() {
    for ( let i = 0; i < scene.children.length; i ++ ) {
        if  (scene.children[i].material) {
            scene.children[i].material.opacity = 1;
        }
    }
}

//raycast hover
function hoverObject() {
    raycaster.setFromCamera( pointer, camera );
    const intersects = raycaster.intersectObjects( scene.children );
    for ( let i = 0; i < intersects.length; i ++ ) {
        intersects[ i ].object.material.transparent = true;
        intersects[ i ].object.material.opacity = 0.75;
    }
}

function animate() {
    controls.update()
    requestAnimationFrame( animate );
    camera.lookAt(ground.position)
    resetMaterials()
    hoverObject()
    renderer.render( scene, camera );

}
animate();

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
    }
   
//on pointer mover
function onPointerMove( event ) {
    pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}

window.addEventListener('resize', onWindowResize); 
window.addEventListener( 'mousemove', onPointerMove, false );

const boxGeometry = new THREE.BoxGeometry(6, 6, 6);
const boxMaterial = new THREE.MeshPhongMaterial( { color: 0xffc000 } );
const box = new THREE.Mesh( boxGeometry, boxMaterial);

box.position.set(0,3,0);

scene.add(box);

change javascript let by html click event

<%- include(“partials/header”) %>

this is main page

<% let cpp= 6 %>
<%  for (let i=0;i<cpp;i++){ %>
    <div class="card">
    <li><%= cards[i].name %></li>
    <li><%= cards[i].price %></li>
    <li><%= cards[i].title %></li>
    <li><%= cards[i].inStore %></li>
    <li><%= cards[i].code %></li>
</div>
    <% } %>

button id=”next”>load more

<%- include("partials/footer") %>

how i can change let cpp=6 to cpp=12 on clicking button id=”next”

Expo error while choosing template: Could not get npm url for package

Error:

Laptop:~/Documents/react$ expo init PasswordManager
✔ Choose a template: › blank               a minimal app as clean as an empty canvas
✖ Something went wrong while downloading and extracting the template.
Could not get npm url for package "expo-template-blank"

I am trying to set up React Native in my Linux Mint. I tried using sudo expo init PasswordManager but it was same, I tried doing sudo npm config set registry https://registry.npmjs.org/ and npm install expo-template-blank

Node version: v16.14.0