Testing React/Jest component with Window.onload

I’m testing a functional component that uses Window.onload to stay on a certain page. Example of the code

function SignUpForm(props) {

  const history = useHistory();
  const {setOnPage } = props;
  window.onload = setOnPage("/registrarse")

My test is:

import React from 'react'
import Enzyme from "enzyme";
import { screen, render } from '@testing-library/react'

import SignInScreen from './SignInScreen'
import Adapter from "enzyme-adapter-react-16"

const { shallow } = Enzyme; 

Enzyme.configure({ adapter: new Adapter() })

describe('Test for login in form', () => {
    test("renders correctly", () => {
        shallow(<SignInScreen/>);
      });
});

The error is in the line of Window.onload, I have not been able to find any solution that can help me.

setOnPage is not a function

Material table data prop and redux

So Hi i am trying to render columns and rows in material table which are loaded from redux.

Let my try to explain

const data = useKPIReport(_ => _.data) // from redux

<TableContainer>
        <MaterialTable
          tableRef={tableRef}
          columns={options.columns}
          options={}
           data={
            async (query) => {
              const {
                page,
                pageSize
              } = query
              try {
                const fetchReport = async () => {
                  try {
                    const result = await postReport({
                      startDate: startDateEpoch / 1000,
                      endDate: endDateEpoch / 1000,
                      page: page + 1,
                      pageSize,
                      accountId
                    })
           
                    const { rows, totalRowsCount } = data // this is important data from redux
                    return {
                      columns: formattedCols,
                      totalCount: totalRowsCount,
                      rows
                    }
                  } catch (e) {
                    console.error(e)
                    return handleError()
                  }
                }
                const result = await fetchReport()
          
                return ({
                  data: result.rows,
                  page,
                  totalCount: result.totalCount,
                })
              } catch (e) {
                console.error(e)
                dispatch(snackbarMessagesAction({
                  severity: 'error',
                  messages: [t('Failed to fetch report')]
                }))
                return ({
                  data: [],
                  page: 0,
                  totalCount: 0
                })
              }
            }}

So overall postReport() method it doesn’t return any results, it sends data to redux, and look like redux is updated later so it’s not possible return results in time.

Any idea how to tackle this in data prop, i have tried something with useEffect:

 React.useEffect(() => {
    tableRef.current && tableRef.current.onQueryChange()
  }, [data])

but feeling this is not possible, i need some general idea usually API endpoint (“postReport()”) returns results but that is not option for me since i am storing results into redis, and later redux is updated via server side event.

Regex to ignore digits before and after a number but accept the number in standalone? [duplicate]

Can someone help me with a regular expression? How can I write one in JS that will accept:

“42”
“42 is my favorite number”
“I have 42 cats”
“I really like 42”

But reject
“12342”
“423”
“14211”
“167889994442113233”
Etc.

I tried D*42D* but no dice.. it’s been keeping me up! Any tips? It’s been a few years since I covered regexs

How to make the content of a div go from left to right, then drop e continue going left to right

I have a code where I want to make the content inside the div, go from left to right (wich I did using Flex-direction: row) and when it gets to the limit of the div, goes down and continues this order. It should look like this (https://i.stack.imgur.com/L97y0.png) with the elements inside going in this order.

I’m using MVC core, and its a system wich accepts requests and shows then in the screen.

Heres the HTML of the div

<div class="pedido-tudo">
            @foreach(var pedido in Model)
        {
            <div class="pedido-quadrado">
                @pedido.IdPedido
                @pedido.NomeCliente
                @pedido.TelCliente
                @pedido.DataEntrada
                @pedido.HoraEntrada
                @pedido.HoraSaida
                @pedido.TextoStatus
                @pedido.TextoTipoPedido
                    
                @if (@pedido.TextoStatus == "Andamento" && @pedido.HoraSaida == "")
                {
                <div class="botoes-cad">
                    <a href="/Pedidos/Update/@pedido.IdPedido" class="btn btn-sm btn-primary" id="finalizar">Finalizar</a>
                </div>
                }
            </div>
        } 
        </div>

the css of the div

.pedido-tudo {
    margin-left: 1.5rem;
    width: 60rem;
    max-width: 60rem;
    display: flex;
    flex-direction: row;
}

.pedido-quadrado{
    margin-top: 1rem;
    margin-left: 5.7rem;
    width: 18rem;
    height: 20rem;
    border: 1px rgb(170, 0, 0) solid;
    color: black;
    font-size: 16px;
}

Heres how currently its

https://i.stack.imgur.com/KIdhq.png

Conditionally Rendering Material UI Elements in React

I want to render Material UI Elements like Menu Items of a AppBar Conditionally if some conditions are true. In my example menu items should only be rendered for specific users. But it doesnt work like the way it would work with normal html in react.

                  {context.token && context.userRole === "USER" && (
                    <MenuItem key="submission" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submission</Typography>
                    </MenuItem>
                  )}
                  {context.token && context.userRole === "JUDGE" && (
                    <MenuItem key="submissions" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submissions</Typography>
                    </MenuItem>
                  )}

Its rendering this Items all the time anyways and seems to ignoring the conditions.

The full code:

import React from "react";
import { NavLink } from "react-router-dom";
import AuthContext from "../context/auth-context.js";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import Menu from "@mui/material/Menu";
import MenuIcon from "@mui/icons-material/Menu";
import Container from "@mui/material/Container";
import Avatar from "@mui/material/Avatar";
import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip";
import MenuItem from "@mui/material/MenuItem";
import ComputerIcon from "@mui/icons-material/Computer";

const ResponsiveAppBar = (props) => {
  const pages = ["Conditions", "Winner", "Submission", "Submissions", "Login"];
  const settings = ["Profile", "Settings", "Logout"];

  const [anchorElNav, setAnchorElNav] = React.useState(null);
  const [anchorElUser, setAnchorElUser] = React.useState(null);

  const handleOpenNavMenu = (event) => {
    setAnchorElNav(event.currentTarget);
  };
  const handleOpenUserMenu = (event) => {
    setAnchorElUser(event.currentTarget);
  };

  const handleCloseNavMenu = () => {
    setAnchorElNav(null);
  };

  const handleCloseUserMenu = () => {
    setAnchorElUser(null);
  };

  return (
    <AuthContext.Consumer>
      {(context) => (
        <AppBar position="static">
          <Container maxWidth="xl">
            <Toolbar disableGutters>
              <Typography
                variant="h6"
                noWrap
                component="div"
                sx={{ mr: 2, display: { xs: "none", md: "flex" } }}
              >
                <ComputerIcon />
              </Typography>

              <Box sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}>
                <IconButton
                  size="large"
                  aria-label="account of current user"
                  aria-controls="menu-appbar"
                  aria-haspopup="true"
                  onClick={handleOpenNavMenu}
                  color="inherit"
                >
                  <MenuIcon />
                </IconButton>
                <Menu
                  id="menu-appbar"
                  anchorEl={anchorElNav}
                  anchorOrigin={{
                    vertical: "bottom",
                    horizontal: "left",
                  }}
                  keepMounted
                  transformOrigin={{
                    vertical: "top",
                    horizontal: "left",
                  }}
                  open={Boolean(anchorElNav)}
                  onClose={handleCloseNavMenu}
                  sx={{
                    display: { xs: "block", md: "none" },
                  }}
                >
                  {context.token && context.userRole === "USER" && (
                    <MenuItem key="submission" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submission</Typography>
                    </MenuItem>
                  )}
                  {context.token && context.userRole === "JUDGE" && (
                    <MenuItem key="submissions" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submissions</Typography>
                    </MenuItem>
                  )}
                  <MenuItem key="conditions" onClick={handleCloseNavMenu}>
                    <Typography textAlign="center">Conditions</Typography>
                  </MenuItem>
                  <MenuItem key="winner" onClick={handleCloseNavMenu}>
                    <Typography textAlign="center">Winner</Typography>
                  </MenuItem>
                </Menu>
              </Box>
              <Typography
                variant="h6"
                noWrap
                component="div"
                sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}
              >
                LOGO
              </Typography>
              <Box sx={{ flexGrow: 1, display: { xs: "none", md: "flex" } }}>
                {pages.map((page) => (
                  <Button
                    key={page}
                    onClick={handleCloseNavMenu}
                    sx={{ my: 2, color: "white", display: "block" }}
                  >
                    {page}
                  </Button>
                ))}
              </Box>

              <Box sx={{ flexGrow: 0 }}>
                <Tooltip title="Open settings">
                  <IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
                    <Avatar
                      alt="Remy Sharp"
                      src="/static/images/avatar/2.jpg"
                    />
                  </IconButton>
                </Tooltip>
                <Menu
                  sx={{ mt: "45px" }}
                  id="menu-appbar"
                  anchorEl={anchorElUser}
                  anchorOrigin={{
                    vertical: "top",
                    horizontal: "right",
                  }}
                  keepMounted
                  transformOrigin={{
                    vertical: "top",
                    horizontal: "right",
                  }}
                  open={Boolean(anchorElUser)}
                  onClose={handleCloseUserMenu}
                >
                  {settings.map((setting) => (
                    <MenuItem key={setting} onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">{setting}</Typography>
                    </MenuItem>
                  ))}
                </Menu>
              </Box>
            </Toolbar>
          </Container>
        </AppBar>
      )}
    </AuthContext.Consumer>
  );
};

export default ResponsiveAppBar;

Fetching multiple raw md files from GitHub in React JS

I’m trying to fetch data from multiple raw .md files from Guthub repo. Currently I’m able to fetch only one, yet I need to get to all of them.

I have a github repo and Im looking to fetch data from raw .md file, which is not a problem. The problem is that the repo has bunch of folders and each folder has its own .md file. I need to make some sort of map through all folders and fetch all of the .md files.

Lets say I have a github repo with following folders:

folder1 -> text1.md
folder2 -> text2.md
folder3 -> text3.md

I’m currently being able to fetch only one raw md usinng the following method

let fetchData = () => {    
axios.get("https://raw.githubusercontent.com/user-name/repo-name/master/folder1/text1.md").then(response => {
      console.log(response)
    }).catch(error => {
      console.log(error)
    })
  }

My goal is to fetch all text1, text2, text3.md so I can map through them and display in the table

HTML textarea connect

I have a question. I am making a note-taking/study app for myself as a project to learn CSS HTML and javascript so I am new to all of this, so my question is I have a main text area then another one on top to represent the title and then I have a sidebar to make new pages I’m working on. How can I make it so when I type the title in the text both textbox or just text will change with it?Heres an image of the page right now I want those untitled texts to change togehter

How can I preserve the JSDoc on re-assignment in VSCode?

A project I am on uses plugins, which export objects, and have their properties re-assigned to centralise functions.

Here is an example:

// barPlugin.js
const barPlugin = {
  /**
   * Register a Foo
   * @param {string} name of the foo
   * @param {object} options the options that make this foo special
   * @param {string} options.flavour how the foo tastes
   * @param {boolean} options.levitate if the foo can levitate
   */
  registerFoos: (name, options = {}) => {
     // stuff that registers foos
  }
  // other bar plugin related functions
}
export default barPlugin;

// pluginHub.js
const allPlugins = {};
export const initialisePlugins = () => { // called on app load
  // hovering over 'registerFoos' on the LHS of the assignment does not show the jsdoc
  allPlugins.registerFoos = barPlugin.registerFoo; 
  // LOTS of other examples of the above
}
export default allPlugins;

This is also so that when we need to register/interact with the foos registered via the barPlugin we only need to know it’s foos and not which of the many many plugins it’s from.

The issue, now that we have started using JSDoc is that it seems like importing allPlugins and calling allPlugins.registerFoos no longer has the JSDoc associated with it?

// nonPluginCode.js
import allPlugins from 'pluginsHub';

allPlugins.registerFoos( ... ) // hovering over 'registerFoos' does not show the jsdoc

It feels like this might be an issue with VSCode, but regardless how can I preserve the JSDoc across the reassignment?

It’s not JSDoc broken on `exports.default` in VSCode? as this happens before exporting.

Server Error while using Graphql Playground

I have been following the www.howtographql.com tutorials but i am stuck as i am not able to add authorization token in http headers. As soon as i write the authorization token it gives an error – ‘Server cannot be reached’

index.js

const { ApolloServer } = require('apollo-server');
const { PrismaClient } = require('@prisma/client');
const fs = require('fs');
const path = require('path');
const { getUserId } = require('./utils');
const Query = require('./resolvers/Query');
const Mutation = require('./resolvers/Mutation');
const User = require('./resolvers/User');
const Link = require('./resolvers/Link');

const prisma = new PrismaClient();

const resolvers = {
    Query,
    Mutation,
    User,
    Link
}

const server = new ApolloServer({
    typeDefs: fs.readFileSync(
        path.join(__dirname, 'schema.graphql'),
        'utf-8'
    ),
    resolvers,
    context:({ req }) => {
        return {
            ...req,
            prisma,
            userId: req && req.headers.authorization ? getUserId(req) : null
        };
    }
});

server.listen()
    .then(({ url }) => console.log(`Server is running on ${url}`)
    );

increase textarea size according to the size of the text in the angular

sorry for my English

currently the following code is being used to resize the textarea

    function autoResize(el){
  while (el.scrollHeight > el.offsetHeight){
    el.rows += 1;
  }
}

but it only resizes when I hover over the textarea

<textarea onmousemove="autoResize(this)"></textarea>

I would like to make it resize automatically when I open the screen that has the textarea. I already tried switching to onload but without success

js script for automatic slideshow (html, js)

i’m trying to write a js script for an automatic slideshow of the newest 10 images in a specific folder. It is a folder where every hour a new image is uploaded, so i cant use the name of the image just the time when it was uploaded.

can someone solve this problem?

kind regards

Hide table row based on table cell pure Javascript

I have an form which add the input to an HTML table. I want to do a dropdown where the user can filter for specific table cell elements only in pure Javascript and a filter method.

Let’s say I have an table like this:

Name | Age | ID

Anna | 14 | 3

Herb | 34 | 4

John | 14 | 6

And a dropdown like this:

Select Name

  • Anna
  • Herb
  • John

In the case the user selects Anna only the following table should showed:

Name | Age | ID

Anna | 14 | 3

The tricky part is that every row is created through the input from an form what means that I can’t talk to an specific table row per id or class.

Here is what I tried:

Table

<table id="table" class="tableZebra" border="1">
    <tr>
        <th>Student_Id</th>
        <th>First_Name</th>
        <th>Last_Name</th>
        <th>DOB</th>
        <th>Gender</th>
        <th>Department</th>
        <th>Email_Id</th>
        <th>Joining Date</th>
    </tr>
</table>                           

Form

<form">
    <p>*Staff_Id:</p>
    <div><input type="text" id="Staff_Id" placeholder="Staff_Id"></div>
    <p>*First_Name:</p>
    <div><input type="text" id="First_Name_staff" placeholder="First_Name"></div>
    <p>Last_Name:</p>
    <div><input type="text" id="Last_Name_staff" placeholder="Last_Name"></div>
    <p>DOB:</p>
    <div><input type="text" id="DOB_staff" placeholder="DOB"></div>
    <p>Gender:</p>
    <div><input type="radio" id="GenderFemale_staff" placeholder="Gender" name="test"></div>
    <label for="html">Female</label>
    <div><input type="radio" id="GenderMale_staff" placeholder="Gender" name="test"></div>
    <label for="html">Male</label>
    <p>*Email_Id:</p>
    <div><input type="text" id="Email_Id_staff" placeholder="Email_Id"></div>
    <div class="distance-submit"><input class="submit" type="submit" value="Submit" onclick="onClickCheckFormStaff()"></div>
    <div class="error-staff" id="error-staff">*Fill out all mandatory fields</div>
</form>

Select button

<p>*Department:</p>
<select name="departments" id="Departments">
    <option value="empty">------</option>
    <option value="Department_1">Department_1</option>
    <option value="Department_2">Department_2</option>
    <option value="Department_3">Department_3</option>
    <option value="Department_4">Department_4</option>
</select>

JS

function changeDisplayTable(){
    //here i get all the values from the table cell departments in an array as text
    var dataCellsDepartments = document.getElementsByClassName(" dep"); //if does not work try " dep"
    var listWithTextContentDepartments = [];
    var i = 0;
    len = dataCellsDepartments.length;
    while(i < len){
        listWithTextContentDepartments.push(dataCellsDepartments[i].textContent)
        i++
    }
    console.log(listWithTextContentDepartments);
    //array filtern und dann durch jede row gehen und checken if row contains one of the elem from array
    const result = listWithTextContentDepartments.filter(checkDepartment);
    function checkDepartment(department){
        return department
    }

    //wenn selected elem != elem from table row --> hide table row

}

For the Javascript part I tried to get all the elements from the table cell which should contain the value from the select button and if this element is != the value from the select button I hide the table row. I don’t know how to get the table row through a table cell element.

How to split an array to multiple arrays one by one JS

I need to split an Array into multiple arrays one by one, for example, if I have an array

const input = [1, 2, 3, 4, 5, 6, 7, 8, 9];

And the number of multiple arrays would be 3, the output should be

const arraysNumber = 3;
const result = [[1,4,7], [2,5,8], [3,6,9]];

if multiple arrays = 2,

const arraysNumber = 2;
result = [[1,3,5,7,9], [2,4,6,8]];

if multiple arrays = 4,

const arraysNumber = 4;
result = [[1,5,9], [2,6], [3,7], [4,8]];

I found only ways hot to split on chunks, like [[1,2,3], [4, 5, 6], [7, 8, 9]], but that’s not what I need

Would be grateful for any help!

‘Routes’ is not defined react/jsx-no-undef

So I was following the React Crash Course on YouTube for Beginners from Academind. I was following everything along and everything was good until I came to the Routing part.
I followed every step, everything just perfectly (for the routing part) but after refreshing the page the following error occurs:

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Aaand I did it, I wrapped my Route in Routes :

    import { Route } from 'react-router-dom';


import AllMeetupsPage from './Pages/AllMeetups';
import NewMeetupsPage from './Pages/NewMeetups';
import FavoritesPage from './Pages/Favorites';

function App() {
  return (
    <div>
      <Routes>
        <Route path='/'>
          <AllMeetupsPage />
        </Route>

        <Route path='/new-meets'>
          <NewMeetupsPage />
        </Route>

        <Route path='/favs'>
          <FavoritesPage />
        </Route>
      </Routes>
    </div>
  );
}

export default App;

and then I get this:

‘Routes’ is not defined react/jsx-no-undef

then I :

Tried to import Routes from react-router-dom – No success;

Tried to import Routes from react-router – No success;

Tried to import Routes also in different components – No success;

Trust me I tried every different scenario for Routes but couldnt achieve anything different.
I

Googled, researched and couldnt find the solution for this problem.. Now Im desperate and
stuck here and I cant continue my React learning journey if I dont fix this…