React: Error passing props to functional child components inside class parent component

In my React Native app I have a class component Parent and in it I define two functional components ChildA and ChildB. This works without errors:

class Parent extends Component {
  const ChildA = () => {
    return <View a={this.props.a} b={this.props.b} c={101}/>
  }
  const ChildB = () => {
    return <View a={this.props.a} b={this.props.b} c={102}/>
  }
}

I want to modularize this by creating GenericChild like this:

class Parent extends Component {
  const GenericChild = (props) => {
    return <View a={this.props.a} b={this.props.b} c={props.c}/>
  }
  const ChildA = () => {
    return <GenericChild c={101}/>
  }
  const ChildB = () => {
    return <GenericChild c={102}/>
  }
}

This throws the error Cannot read properties of undefined (reading 'apply').

What did I do wrong?

How to pass data to Textbox A in Playwright test using async function enterA?

I have extracted function

async function enterA(page, a){
  console.log(`Entering ${a}`);
  const textboxA = await page.$('#value1');
  await textboxA.type(a.toString());
}

from the Playwright test

test('simple form', async ({ page }) => {
  console.log(`Navigating to ${simpleFormUrl}`);
  await page.goto(simpleFormUrl);

  const a = 3;
  const b = 2;
  var expectedResult = a + b;
  
  enterA(page, a);
  
  const textboxB = await page.$('#value2');
  await textboxB.type(b.toString());

and Textbox A is no longer filled with data. The value a is correctly passed to the function. When lines from function enterA were inline inside test function, everything worked fine. Filling Textbox B works correctly.

I tried to make function enterA return also the variable page, but the result was the same.

Closures and loops JavaScript. How depth is closure?

https://jsfiddle.net/b65j3d8o/4/

function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {

  let helpText = [
    {'id': 'email'},
    {'id': 'name'},
    {'id': 'age'}
  ];
  
  for(let w = 0; w<1; w++){
    for(let f = 0; f<1; f++){
        let o = {c: 0}; // o is in shared context, every callback has access to the same o object
      for (let i = 0; i < helpText.length; i++) {
                //let o = {c: 0}; // o is in seperated context, every callback has access to different o object
        for(let j = 0; j<3; j++){
          if(i==j){
            document.getElementById(helpText[i].id).onfocus = function() {
              o.c++;
              showHelp(o.c);
            }
          }
        }
      }
    }
  }
  
  
}

setupHelp();

Depending how depth o object is declared, is shared in the same closure for all callbacks (when is declared in outer loop) or is in seperated context(every callback has access to own instance of o) – when declared in inner loop.

o has different behavior depending how depth is nested
How to explain this?

setTimeout/clearTimeout for ‘timer’ event on GTM

I has been trying to track user engagement on podcasts in a website using custom HTML tag on GTM.
But getting stuck in the tracking for auto-play property.

Scenario: a listener is able to auto-play from podcast to podcast. That kinda behavior leads to missing events since as of now, all events (start, play, pause, play next) are triggered by click action

Problem: the below code seemingly clears the timeout from the beginning, even when there is no ‘click’ event happening. I do not wanna declare another setTimeout function after clearTimeout as do not know how long the pause is.

Code:

<script>
 
var initial = setTimeout(function(){
  dataLayer.push({
  'event': 'gtm.timer'
  })
  }, 10000);
  
{{Click Element}}.closest('.play-pause-button').addEventListener('click',function(){
  clearTimeout(initial);
  
  })
  
</script>

My idea: employing timer event.
Specifically, I will set timeout for ‘timer’ event, after a 80% podcast duration, that event will be pushed into datalayer which simultaneously triggers a tag.
But the challenge is that the listener could pause in the middle of podcast, so I wanna clear timeout every time user clicks on ‘play/pause’ button to pause.

The timer should only be reset when user clicks on ‘play/pause’ button to resume his listening.

Could you please help give me some insights?
Thanks

Why isn’t my pop up working on my feature layers?

So I am creating a web application and I have included a pop up to display information from the table in my feature layer but it doesn’t pop up. Can you please tell me why and how do I go about fixing this?

I want it to be like this template: https://developers.arcgis.com/javascript/latest/sample-code/popup-custom-action/

Here is my code: https://codepen.io/chesouye/pen/XWxyRvx

I have rearranged the template (without the other elements in my regular code that can be found in my codepen), and it works exactly how I want it to:

  <html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>
      Custom popup actions per feature attribute | Sample | ArcGIS Maps SDK for
      JavaScript 4.26
    </title>
    
    <style>
      body {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
        overflow: hidden;
      }
    
      #viewDiv {
        position: absolute;
        right: 0;
        left: 0;
        top: 0;
        bottom: 0;
      }
    </style>

    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.26/esri/themes/light/main.css"
    />
    <script src="https://js.arcgis.com/4.26/"></script>

    <script>
      require(["esri/Map", "esri/views/MapView", "esri/layers/FeatureLayer"], (
        Map,
        MapView,
        FeatureLayer
      ) => {
        const map = new Map({
          basemap: "streets-navigation-vector"
        });

        const view = new MapView({
          container: "viewDiv",
          map: map,
          center: [-77.2627, 18.0927],
          zoom: 10
        });

        /********************
         * Add feature layer
         ********************/
        // sampling of breweries
        const featureLayer = new FeatureLayer({
          url: "https://services6.arcgis.com/3R3y1KXaPJ9BFnsU/arcgis/rest/services/ECJWEB_MAP/FeatureServer/3",
          popupTemplate: {
            title: "{OFFICE_NAME}",
            lastEditInfoEnabled: false,
            actions: [
              {
                id: "find-brewery",
                image:
                  "https://developers.arcgis.com/javascript/latest/sample-code/popup-custom-action/live/beer.png",
                title: "Brewery Info"
              }
            ],
            content: [
              {
                type: "fields",
                fieldInfos: [
                  {
                    fieldName: "LOCATION"
                  },
                  {
                    fieldName: "OFFICE_TYPE",
                    label: "Office Type"
                  },
                  {
                    fieldName: "city"
                  },
                  {
                    fieldName: "state"
                  },
                  {
                    fieldName: "phone"
                  },
                  {
                    fieldName: "website"
                  }
                ]
              }
            ]
          }
        });

        map.add(featureLayer);

        view.when(() => {
          // Watch for when features are selected
          view.popup.watch("selectedFeature", (graphic) => {
            if (graphic) {
              // Set the action's visible property to true if the 'website' field value is not null, otherwise set it to false
              const graphicTemplate = graphic.getEffectivePopupTemplate();
              graphicTemplate.actions.items[0].visible = graphic.attributes
                .website
                ? true
                : false;
            }
          });

          const popup = view.popup;
          popup.viewModel.on("trigger-action", (event) => {
            if (event.action.id === "find-brewery") {
              const attributes = popup.viewModel.selectedFeature.attributes;
              // Get the 'website' field attribute
              const info = attributes.website;
              // Make sure the 'website' field value is not null
              if (info) {
                // Open up a new browser using the URL value in the 'website' field
                window.open(info.trim());
              }
            }
          });
        });
      });
    </script>
  </head>

  <body class="light">
    <div id="viewDiv" class="esri-widget"></div>
  </body>
</html>

Assign value from succesfull promise resolve to mutable ref object in react

I’m creating a random movie generator, for that I’m calling an external API to get the movies, and then I’m selecting one movie from the returned list. I managed to make it work like this:

export default function Page() {
  const [movie, setMovie] = useState<Movie>({
    title: ""
  })

  useEffect(() => {
    setNewMovie()
  }, [])

  function setNewMovie() {
    getMoviesRequest().then((newMovies) => {
      const randomIndex = getRandomInt(9)
      const movie = newMovies[randomIndex]
      setMovie(movie)
    })
  }

  return (
    <div>
      <h3>
        {movie.title}
      </h3>
      <button onClick={setNewMovie}>
        Generate New Movie
      </button>
    </div>
  )
}

The problem with this code is that it has to call the API every time I want to set a new movie, which is not ideal since it takes longer to run. What I would like to do is call the API once within the useEffect hook and have the returned movies stay the same throughout the hole lifetime of the component so that I don’t have to pull the list of movies on every render. I’m using useRef to achieve this, here’s what I’ve tryied:

export default function Page() {
  const movies = useRef<Movie[]>([])
  const [movie, setMovie] = useState<Movie>({
    title: ""
  })

  useEffect(() => {
    setNewMovies()
    setNewMovie()
  }, [])

  function setNewMovies() {
    getMoviesRequest().then((newMovies) => {
      movies.current = newMovies
    })
  }
  function setNewMovie() {
    const randomIndex = getRandomInt(9)
    const movie = movies.current[randomIndex]
    setMovie(movie)
  }

  return (
    <div>
      <h3>
        {movie.title}
      </h3>
      <button onClick={setNewMovie}>
        Generate New Movie
      </button>
    </div>
  )
}

This isn’t working since if I try to access the current value of movies outside the promise It seems to not have been updated.

I looked for answers and I found that you can’t really access the value of the promise from outside unless you are on an async function, but I already tryied that and I get the same result:

async function setNewMovies() {
  movies.current = await getMoviesRequest()
}

Is there a way to achieve what I’m trying to do?
Thank you!

Is it possible to set up WebPack’s devServer with HMR or similar to live reload/replace plain JS methods?

We have correctly got WebPacks devServer to reload and replace React things with the react-refresh plugin, and I am wondering if the same is possible for plain JavaScript code. All our code is in exported functions, so I would think at least theoretically it should be possible to replace changed code without a full reload (which for us is costly).

Searching, I found many references to reload/replace React things, as well as to automatically do a full reload of recompiled plain JavaScript, but not the partial hot replacement I’ve seen with the React components.

Is what I want not possible for plain JS/JS without a framework to facilitate the replacing ?

handle order in the vue.js

fetchData(index: number | null, instance?: null) {

    if (this.firstLoad) {
      this.loading = true;
    }
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }

    // @ts-ignore
    console.log('lili' + JSON.stringify(instance.routeName, null, 2));
      // @ts-ignore
      instance.fetchData(index, this.search.query, this.perpage)
        .then((response: any) => {
          this.response = response;
          if(instance) {
            // @ts-ignore
            console.log('bili' + JSON.stringify(instance.routeName, null, 2));
            // @ts-ignore
            this.storeRoutes.push(modulesMetaData[instance.routeName]);
            this.storeInstances.push(instance);
          }
          this.items.push(this.response.data);
          this.search.current = this.search.query;
          if (!response) {
            showToaster('danger', '', 'Failed to fetch Data', response.code);
          }

        })
        .catch((error: any) => {
          console.log(error);
        })
        .finally(() => {
          this.loading = false;
          this.firstLoad = false;
        });

  }

i have this code, those print lines give me this:

lili"zones"
lili"zoneCategory"
bili"zoneCategory"
bili"zones"

but what i want is

lili"zones"
lili"zoneCategory"
bili"zones"
bili"zoneCategory"

which means i want to handle orders in the correct way and get items per certain order, any suggestions?
………………

AR mode in A-Frame shows black background instead of phone camera view, how do I fix it?

Can’t hide scene models except one in AR mode in aframe.

I was toggling visible: false to all entities that I wanted to hide in the 1.0 version but in 1.4 it doesn’t work as before.
Right now I can see a black background around in the AR mode instead of phone camera view.

Setting background="transparent" or background="color: transparent (or any other color except black)" for the a-scene doesn’t help. Also there aren’t any errors or warnings after enabling AR mode. Right after “AR” button click I can see my phone’s camera view for several seconds before black background appears.

What can this be?

I don’t use ar.js or any other libraries.

Sorry if my description isn’t very informative. I can provide more details if necessary.

React native ActivityIndicator appearing after async load from database instead of before

I use an ActivityIndicator to show the user of my native React app that data is being retrieved from the database.
So in this case, the user selects a vehicle generation with the Picker and I retrieve all the vehicle types for that generation.
The problem is that the ActivityIndicator is not displayed directly, but a few seconds after the selection, after the data has been loaded from the database and I dont know why.These are the relevant code snippets:

const [isLoading, setIsLoading] = useState(false);
...
const getAllTypesForGeneration = async (generationId) => {
  console.log("Getting types...");
  const types = await DataStore.query(CarType, (type) =>
    type.carGenerationID.eq(generationId)
  );
  setAllTypes(types);
  console.log("Got types...");
  setIsLoading(false);
};
...
return (
  <View>
    <View style={styles.activity}>
      <ActivityIndicator
        animating={isLoading}
        size="large"
        color={colors.primary}
      />
    </View>
   ...
    <Picker
      mode="dropdown"
      onValueChange={(itemValue, itemIndex) => {
        if (itemValue !== "") {
          setIsLoading(true);
          setSelectedCarGeneration(allGenerations[itemIndex - 1]);
          getAllTypesForGeneration(itemValue);
        }
      }}
    >
  ...
  </View>
);

Pass two parameter to payload in dispatch

im react beginner and im struggling to edit a task or transaction in todo APP
i googled how to do it and they said to add to payload 2 parameters like this (payload: {id,text}
and in reducer case i call it by action.payload.id/action.payload.text but its not working for some reason i dont know
[dispatch-code],case-logic

i tried to pass the two parameters to case’s logic but with no luck

How to fix CSP error? “Refused to execute inline event handler because it violates the following Content Security Policy directive…”

This is the CSP I’m setting –
Content-Security-Policy: default-src 'none'; script-src 'self' 'unsafe-eval' 'nonce-b1967a39a02f45edbac95cbb4651bd12' 'unsafe-hashes'; frame-src 'self' 'nonce-b1967a39a02f45edbac95cbb4651bd12' 'unsafe-hashes'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; object-src 'self'; font-src 'self' data:;

and my JS file content is –

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> WebHelp Navigation Mini-bar </title>



<style>
<!--
body {margin:0;}
-->
</style>
<script nonce='testData'  src="whver.js" charset="utf-8"></script>
<script nonce='testData'  src="whutils.js" charset="utf-8"></script>
<script nonce='testData'  src="whmsg.js" charset="utf-8"></script>
<script nonce='testData'  src="whproxy.js" charset="utf-8"></script>
<script nonce='testData'  src="whmozemu.js" charset="utf-8"></script>
<script nonce='testData'  src="whtbar.js" charset="utf-8"></script>
</head>
<body marginheight="0"  marginwidth="0"  bgcolor="#363f48"    background="background.png"  scroll="no">
<script nonce='testData' language="javascript1.2">
<!--
if (window.gbWhTBar)
{
    setButtonFont("avprev","Arial","11pt","#a7abaf","Normal","Normal","none");
setButtonFont("avnext","Arial","11pt","#a7abaf","Normal","Normal","none");
setButtonFont("rolesel","Arial","11pt","#a7abaf","Normal","Normal","none");
setButtonFont("synctoc","Arial","11pt","#a7abaf","Normal","Normal","none");
setButtonFont("hide2","Arial","11pt","#a7abaf","Normal","Normal","none");

    gsIPrev = "wht_prev.gif";
    gsIPrevD = "wht_prev_g.gif";
    gsINext = "wht_next.gif";
    gsINextD = "wht_next_g.gif";
    gsISync = "wht_sync.gif";
    gsIHide = "wht_hide.gif";
    setBackgroundcolor("#363f48");
    setBackground("background.png");
    
    addButton("avprev",BTN_TEXT|BTN_IMG,"","","","","",0,0,"previous-enabled.png","","","previous-disabled.png","","");
addButton("avnext",BTN_TEXT|BTN_IMG,"","","","","",0,0,"next-enabled.png","","","next-disabled.png","","");
addButton("rolesel",BTN_TEXT|BTN_IMG,"","","","","",0,0,"","","","","","");
addButton("synctoc",BTN_TEXT|BTN_IMG,"","","","","",0,0,"sync-toc.png","","","sync-toc.png","","");
addButton("hide2",BTN_TEXT|BTN_IMG,"","","","","",0,0,"hide.png","","","hide.png","","");

    addButton("blankblock");
    writeStyle(true);
    ReSortMinibarButtons();
}
else
    document.location.reload();

if (window.gbNav6)
{
    var oMsg=new whMessage(WH_MSG_RELOADNS6,null,null);
    notify(oMsg);
}
//-->
</script>
</body>
</html>

After removing ‘unsafe-inline’ from script-src and adding ‘nonce-b1967a39a02f45edbac95cbb4651bd12’ I’m getting this error. Kind of stuck for a long in this issue. Need some guidance. Thanks in advance.