Mocking a Util function that requires a React Dom node

I have this util function that scrolls into view that I’m trying to test. The function (below) checks for a react dom node. I can’t seem to figure out in jest how to test this function by providing the Dom node.

export const scrollIntoView = (node, behavior, block) => {
  if (!node) return;
  const element = ReactDom.findDOMNode(node);
  try {
    if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
      if ("parentIFrame" in window) {
        window.parentIFrame.scrollToOffset(0, 0);
      } else {
        window.scrollTo({ top: 0, behavior: behavior || "smooth" });
      }
    } else {
      element.scrollIntoView({
        behavior: behavior || "smooth",
        block: block || "start",
      });
    }
  } catch (error) {
    element.scrollIntoView(false);
  }
};

Here is my test: When I do the following I get the error: Argument appears to not be a ReactComponent.

it("Should scroll up", () => {
    const mockScrollIntoView = jest.fn(scrollIntoView);
    const node = (document.body.innerHTML = '<App id="root"/>');

    mockScrollIntoView(node);
    expect(mockScrollIntoView).toBeCalledWith({
      behavior: "smooth",
      block: "start",
    });
  });

firebase rules how to make user can read only his data

I use firebase 8.10.0 white Vue Js.

I use only Google as a provider for authentication and I want user to read-only his data, so i use firestore rules:

my rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    
    match /users/{id} {
      allow read: if request.auth.uid == id;
    }
    
  }
  
}

and this is how i get the data:

...

let ref = firebase.firestore().collection("users");

ref.get().then((doc) => {
  this.data = [{id: doc.id}];
})

...

but i get this error: Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

how can i fix that?

Replicate element in React

Hello thanks for the help, with the following code in react I want to replicate the click button every time I click on it. Currently nothing happens, but if the console shows that the array grows. Here the sandbox:

https://codesandbox.io/s/charming-glitter-0ntxmj?file=/src/App.js

const { useEffect, useState } = React;

function App() {
  const btn = [
    <button
      onClick={() => {
        btn.push(btn[0]);
        console.log(btn);
      }}
    >
      Click
    </button>
  ];

  /*  useEffect(()=>{
btn
  },[btn])*/

  return (
    <div className="App">
      <div>
        {btn.map((e) => {
          return e;
        })}
      </div>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

javascript: detect trailing and leading symbols that look like a space or a new line symbols

I know how to write a javascript regex that which would detect space, tab, new line symbols. But how to write a javascript regex that which would detect any trailing or leading symbol (unicode) which is a space (or a tab) or looks like a space symbol (including new line symbols)? Is this even possible in unicode?

a sample of symbols that look like a space symbol

U+0020  SPACE   foo bar Depends on font, typically 1/4 em, often adjusted
U+00A0  NO-BREAK SPACE  foo bar As a space, but often not adjusted
U+1680  OGHAM SPACE MARK    foo bar Unspecified; usually not really a space but a dash
U+180E  MONGOLIAN VOWEL SEPARATOR   foo᠎bar 0
U+2000  EN QUAD foo bar 1 en (= 1/2 em)
U+2001  EM QUAD foo bar 1 em (nominally, the height of the font)
U+2002  EN SPACE (nut)  foo bar 1 en (= 1/2 em)
U+2003  EM SPACE (mutton)   foo bar 1 em
U+2004  THREE-PER-EM SPACE (thick space)    foo bar 1/3 em
U+2005  FOUR-PER-EM SPACE (mid space)   foo bar 1/4 em
U+2006  SIX-PER-EM SPACE    foo bar 1/6 em
U+2007  FIGURE SPACE    foo bar “Tabular width”, the width of digits
U+2008  PUNCTUATION SPACE   foo bar The width of a period “.”
U+2009  THIN SPACE  foo bar 1/5 em (or sometimes 1/6 em)
U+200A  HAIR SPACE  foo bar Narrower than THIN SPACE
U+200B  ZERO WIDTH SPACE    foo​bar 0
U+202F  NARROW NO-BREAK SPACE   foo bar Narrower than NO-BREAK SPACE (or SPACE), “typically the width of a thin space or a mid space”
U+205F  MEDIUM MATHEMATICAL SPACE   foo bar 4/18 em
U+3000  IDEOGRAPHIC SPACE   foo bar The width of ideographic (CJK) characters.
U+FEFF  ZERO WIDTH NO-BREAK SPACE   foobar  0

Azure Media Player, hangs when clicking on the player after source is set but before playing

I am seeing an issue with AMP where there is a small window in which the player can be clicked and it results in it hanging.

Specifically if the player is clicked when the source has been set but before the video has begun playing AMP hangs only displaying the loading icon.

In the browser debug tools I can see failed requests to blob:https://example.com/[guid] where [guid] is different on every request
enter image description here

The initiator tab for the request is empty so no clues there as to where the request is failing.

The source is set as follows

 myPlayer.src([{
                src: data.path,
                type: "application/vnd.ms-sstr+xml",
                protectionInfo: [{
                    type: "AES",
                    authenticationToken: "Bearer=" + data.authToken
                }],
                streamingFormats: ["SMOOTH", "DASH"]
            },]);

The video element as so

 <div id="video-view" className="videoPlayerWithToolbar" >
            <video
                style={{ height: "100%" }}
                id="azuremediaplayer"
                className="azuremediaplayer amp-default-skin amp-big-play-centered videoResponsive"
                tabIndex={0}
                controls
                poster=""
                data-setup='{"logo": { "enabled": false },"techOrder": ["azureHtml5JS", "flashSS", "silverlightSS", "html5"],
                "nativeControlsForTouch": false }' >
            </video>
        </div>

Any thoughts on why I might be seeing this behaviour or how to debug in the absence of any initiator information on the network traffic?

How would I change my source code to fetch images from a JSON file instead using ‘img src’?

I’ve created a website that has numerous img tags. I was wondering if there is a way to fetch the image urls from a JSON file instead of using the img tags without having to Start from scratch.

          <main>

            <div><img src="https://image.tmdb.org/t/p/w500/pNrQaH0ATrz9wFrNpwfB1aU4MpK.jpg"/
</div>
            <div><img src="https://image.tmdb.org/t/p/w500/mYkTq569KOtjdq5zo9mrEY6ecip.jpg"/></div>
            <div><img src="https://image.tmdb.org/t/p/w500/7lyBcpYB0Qt8gYhXYaEZUNlNQAv.jpg"/>

          </main>

Invalid hook call error when trying to use React-pro-sidebar

I’m trying to use the react-pro-sidebar package

https://github.com/azouaoui-med/react-pro-sidebar

However I keep on getting the invalid hook call error

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

For some context, I’m using react with react-router for navigation between pages. I wanted to create a sidebar and populate the menu items with react-router links, but that wasn’t working out. Below is what I have:

import React from 'react'
import { ProSidebar, Menu, MenuItem, SubMenu } from 'react-pro-sidebar';

const fun = <ProSidebar>
    <Menu iconShape="square">
        <MenuItem>Dashboard</MenuItem>
        <SubMenu title="Components">
            <MenuItem>Component 1</MenuItem>
            <MenuItem>Component 2</MenuItem>
        </SubMenu>
    </Menu>
</ProSidebar>; 


const SideBarDashboard = () => {
  return (
    <div>
        {fun}
    </div>
  )
}

export default SideBarDashboard;

I iterate over an array with map and then try to change a boolen of an object from false to true with an onClick. UI doesn’t reflect it but log does

CodeSandbox – https://codesandbox.io/s/distracted-taussig-n7e7q3?file=/src/App.js

As you can see, I iterate over the flaggers array with .map and render <div>true</div> or <div onClick={() => setToTrue(flag)}>false</div>. I assumed that if I were to click the second div, the refer property of that flag would be set to true and the component would re-render, making the div change to <div>true</div> but that doesn’t seem to be the case.

In the setToTrue function I console.log the post object, and I can see that the refer property of the second flag has changed to true, but it is not shown in the UI.

import "./styles.css";

export default function App() {
  const post = {
    flaggers: [
      {
        refer: false
      },
      {
        refer: false
      }
    ]
  }

  const setToTrue = (flag) => {
    flag.refer = true;
    console.log(post)
  }

  return (
    <div className="App">
      {post.flaggers.map((flag) => (
        <div>
          {flag.refer ? <div>true</div> : <div onClick={() => setToTrue(flag)}>false</div>}
        </div>
      ))}
    </div>
  );
}

How I can calculate average value for the same values of an array?

help me please how I can calculate average value for the same values of an array?

Input:

[
{name : "John", age: 10}, 
{name : "John", age: 8}, 
{name : "Tom", age: 20}, 
{name : "Tom", age: 10}, 
{name : "Zorro", age: 5},
{name : "Zorro", age: 15}
]

Expected Output:

    [
    {name : "John", averageAge: 9}, 
    {name : "Tom", averageAge: 15}, 
    {name : "Zorro", averageAge: 10},
    ]

How do I use an “or” in a while loop? [duplicate]

I’m trying to make a prompt tag that will display the imputed number that the user will give. The user is given three numbers to pick (1,2, and 3). If the user inputs a number that doesn’t the match the given options, the prompt will be looped until the user gives a valid input (1, 2, or 3).

answer = prompt ('1, 2, or 3?');

while (answer != "1" || "2" || "3") {
answer = prompt ("1, 2, or 3?");
}

if (answer == "1") {
document.getElementById('para').innerHTML = 'You picked 1!';
} else if (answer == "2") {
document.getElementById('para').innerHTML = 'You picked 2!';
} else if (answer == "3") {
document.getElementById('para').innerHTML = 'You picked 3!';
} 

Detect click event position of an overlapping dot

this is a codepen live demo at here.

1)Click on the gird to add first red point

2)Click on the gird to add second red point

3)Click back on the first red point

Problem: You will see that the coordinates will change or detected as you click the first and second. However, when you click back the the first point, the coordinates is not detected and perhaps because its overlay. May I ask if there is a solution for this and show a demo:)

Example here

.red-dot {
  position:absolute; 
  width:15px; 
  height:15px;
  background:red;
}

Why can’t I remove this class with javascript?

I’m trying to make a skeleton loading screen by having a class ‘skeleton’ on the elements which styles them then removing it with javascript after a timeout. The issue is that i can’t get the javascript to work.

Here’s my javascript to remove the class, why isn’t it working?

const timeout = setTimeout(loading, 3000);

function loading() {
    const element = document.getElementById("skeleton");
    element.classList.remove("skeleton");   
  }

Vue component to change text based on data value

This is the data I get and I what to be able to replace the data content with readable text:

 data: [
    { name: 'discounts_offers', type: 'EMAIL', consent: true },
    { name: 'newsletter', type: 'EMAIL', consent: true },
    { name: 'product_upgrade', type: 'EMAIL', consent: true },
    { name: 'sms_offer', type: 'SMS', consent: true },
    { name: 'post_offer', type: 'POST', consent: true }
  ]

This is my component

  <CommunicationPreference
    v-for="(communication, index) in data"
    :key="index"
    :communication="communication"
  />

Then what I would like to do is if {{ communication.name }} equals 'discounts_offers' to use the text “Discounts and offers” like the images attached. Any solutions for the best approach to this?

enter image description here