Theme.breakpoints is undefined in MUI React

Whenever I try to use theme.brekpoints.up , I always encounter the same error theme.breakpoints is undefined on console. version that I am using are
“@emotion/react”: “^11.9.0”,
“@emotion/styled”: “^11.8.1”,
“@mui/icons-material”: “^5.6.2”,
“@mui/material”: “^5.6.2”,
“@mui/styles”: “^5.6.2”

Here is my NavBar

import styled from '@emotion/styled'
import { AppBar, Badge, InputBase, Toolbar, Typography,Avatar } from '@mui/material';
import FacebookIcon from '@mui/icons-material/Facebook';
import React from 'react';
import { Box } from '@mui/system'
import MailIcon from '@mui/icons-material/Mail';
import NotificationsIcon from '@mui/icons-material/Notifications';


const StyledToolBar = styled(Toolbar)({
  display:"flex",
  justifyContent:"space-between",
});

const SearchBar = styled("div")(({theme}) => ({
    backgroundColor:"white",
    padding:"0 10px",
    borderRadius:"3px",
    width:"40%"
}));

const IconContainer = styled(Box)( ({theme}) => ({
    display:'none',
    gap:"20px",
    alignItems:"center",

}));

const UserBox = styled(Box) ( ({theme}) => ({
  display:'flex',
  gap:"10px",
  alignItems:"center",
  [theme.breakpoints.up("sm")]:{
    display: "flex"
  }
}));
export default function NavBar() {
  return (
    <AppBar position='sticky'> 
      <StyledToolBar>
        <Typography variant='h6' sx={{display:{xs:"none",sm:"block"}}}>
          Mero Book
        </Typography>
        <FacebookIcon sx={{display:{xs:"block",sm:"none"}}}/>
        <SearchBar><InputBase placeholder='Search'/></SearchBar>
        <IconContainer>
          <Badge badgeContent={4} color="error"> <MailIcon /> </Badge>
          <Badge badgeContent={4} color="error"> <NotificationsIcon /> </Badge>
          <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" sx={{width:30,height:30}} />
        </IconContainer>
        <UserBox>
        <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" sx={{width:30,height:30}} />
        <Typography>Remy Sharp</Typography>
        </UserBox>
      </StyledToolBar>
    </AppBar>
  )
}

Here is my App.js

import { Stack } from '@mui/material';
import { Box } from '@mui/system';
import Feed from './Components/Feed';
import NavBar from './Components/NavBar';
import RightBar from './Components/RightBar';
import SideBar from './Components/SideBar';

function App() {
  return (
   <Box>
   <NavBar/>
  <Stack direction="row" justifyContent='space-between' spacing={2}>
  <SideBar/>
   <Feed/>
   <RightBar/>
  </Stack>
   </Box>
  );
}

export default App;

Here is my index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

version

{
  "name": "mui_learn",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@mui/icons-material": "^5.6.2",
    "@mui/material": "^5.6.2",
    "@mui/styles": "^5.6.2",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Multiple Countdowns Not Showing Correctly After 1 Completes

I have a website where I need 3 countdowns. Everything is perfectly fine while all 3 countdowns are running, however, once one is completed, the page only shows 2 of the countdowns and not 3. I would like all 3 countdowns to still be shown with (‘XX Completed’) being the text – XX being the countdown title. Below is the code I have so far:

    <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head> 

<body>
<h2 style="font-weight: bold" id="countdownQuali"></h2>
<h2 style="font-weight: bold" id="countdownSprint"></h2>
<h2 style="font-weight: bold" id="countdownRace"></h2>

<script>

    var countDownQuali = new Date('22 Apr, 2022 19:00 GMT+0400').getTime();
    function calculateQualiCountdown() {
    var now = new Date().getTime();
    var distance = countDownQuali - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    document.getElementById('countdownQuali').innerHTML =
    'Qualifying Starts In ' + days + ' Days ' + hours + ' Hours';
    if (distance < 0) {
    clearInterval(x);
    document.getElementById('countdownQuali').innerHTML =
    'Qualifying Completed';
    }
    }
    var x = setInterval(calculateQualiCountdown, 1000);
    
    var countDownSprint = new Date('23 Apr, 2022 18:30 GMT+0400').getTime();
    function calculateSprintCountdown() {
    var now = new Date().getTime();
    var distance = countDownSprint - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    document.getElementById('countdownSprint').innerHTML =
    'Sprint Starts In ' + days + ' Days ' + hours + ' Hours';
    if (distance < 0) {
    clearInterval(x);
    document.getElementById('countdownSprint').innerHTML =
    'Sprint Completed';
    }
    }
    var x = setInterval(calculateSprintCountdown, 1000);
    
    var countDownRace = new Date('24 Apr, 2022 17:00 GMT+0400').getTime();
    function calculateRaceCountdown() {
    var now = new Date().getTime();
    var distance = countDownRace - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    document.getElementById('countdownRace').innerHTML =
    'Race Starts In ' + days + ' Days ' + hours + ' Hours';
    if (distance < 0) {
    clearInterval(x);
    document.getElementById('countdownRace').innerHTML =
    'Race Completed';
    }
    }
    var x = setInterval(calculateRaceCountdown, 1000);
    </script>
    </body>

    </html>

Any help on this would be great! Thanks

Sequelize collect data from couple of associated tables in one array of objects

I am using Sequelize ORM for Postgres db.
My tables and associations look like:

enter image description here

My associations:

Users.hasMany(Options, {
  foreignKey: 'redirectId'
});
Options.belongsTo(User);

Users.hasMany(Finders, {
  foreignKey: 'redirectId'
});
Finders.belongsTo(User);

How can I make a query using Sequelize to get Users and all associated data from tables Options and Finders in one object (without nested objects). Query result should be:

[
  {
    id: 1,
    name: 'Mark',
    option: 'opt1',
    finder: 'films'
  },
  {
    id: 1,
    name: 'Mark',
    option: 'opt2',
    finder: 'films'
  },
  {
    id: 2,
    name: 'Lalo',
    option: 'opt3',
    finder: 'books'
  },
]

Uncaught TypeError in React

Nothing renders in the screen,

index.css?e42b:22 Uncaught TypeError: _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default(...) is not a function

at Module../src/index.css (index.css?e42b:22)

at Module.options.factory (react refresh:6)

at __webpack_require__ (bootstrap:24)

at fn (hot module replacement:62)

at Module../src/index.js (constants.js:5)

at Module.options.factory (react refresh:6)

at __webpack_require__ (bootstrap:24)

at startup:7


It looks like your post is mostly code; please add some more details.

How to search an array of objects with a keyword that can match values to more than one property using filter

const heroes = [
  {name: "Batman", realName: "Bruce Wayne", universe: "DC"},
  {name: "Superman", realName: "Clark Kent", universe: "DC"},
  {name: "Iron Man", realName: "Tony Stark", universe: "Marvel"},
  {name: "Star Lord", realName: "Peter Quill", universe: "Marvel"},
  {name: "Venom", realName: "Eddie Brock", universe: "Marvel"}
]

function search(lookup){
  const result = heroes.filter(each => {
    return each.name.toLowerCase().includes(lookup.toLowerCase())  || 
           each.universe.toLowerCase().includes(lookup.toLowerCase())
  })
  return result
}
console.log(search("DC"))

If I search by name “Batman” I will return the first object. If I search “DC” I will return the first two objects. I’m getting the results I want but what other ways can I iterate over heroes instead of using the || operator? If I wanted to also search by realName I would have to add another return value and I would appreciate input on how to achieve this.

Does any change in an array gets to change the entire array?

I got into that question by thinking about sorting algorithms.

Does changing an element position inside an array would be the same, at the interpretation, compilation or run-time phases, to recreate the entire array with new elements?
Does it change radically from one language to another?
How does it work?

Imagining a specific case in JavaScript, for example:

let animals = ["monkey","zebra","banana","capybara"];

animals.splice(2,1); // returns ["banana"]

Would it be correct to state that the entire animals array was rewritten? Or is there another type of change type? How would that one and only change work, computation-wise?

It’s stated in Javascript documentation that the .splice() method “takes” an array object, creates a new array without it and returns another one with it as an output, but how does it work?

I’m a begginner, so please have patience, and would like a good reading recommendation if possible to learn more about it. Sorry for the incovenience.

How to fetch user’s tag with id discord.js in variable

I am making a leaderboard system for my bot, and want to display the user’s tag along with their amount of money.

Here is the code

        const lb = users
                  .slice(0)
                  .sort(({ Bobux: a }, { Bobux: b }) => b - a)
                  .map(
                    
                    ({ User, Bobux }, pos) => `${pos + 1}. ${(client.users.cache.get(User)).tag} - ${commaNumber(Bobux)} Bobux`,
                  );
    
              const newnew =     lb.slice(0, 30)
                  const embed = new Discord.MessageEmbed()
                  .setTitle('Global Leaderboard For Most Bobux - Top 30')
                  .setDescription(newnew)

Over here, I map it, and attempt to get the user’s tag with their id (User is the user’s id in the database)

                  .map(
                    
                    ({ User, Bobux }, pos) => `${pos + 1}. ${(client.users.cache.get(User)).tag} - ${commaNumber(Bobux)} Bobux`,
                  );

When I do this, I get the error

0|index  | TypeError: Cannot read properties of undefined (reading 'tag')

How do I fetch the user’s tag with their id.

hover Works in demo but not in practice [duplicate]

http://jsfiddle.net/384k9hng/1/

SO i have this demo that works great! But I put it in my website and it doesn’t work!!!!

$('#test').hover(function() {
    if ($('#hello:hover').length > 0) {
         document.getElementById('hello').textContent = "A god like being, power swirls and mystifies beholder. Thousands of creations wander around the blank room. The room that seems to never end, that cannot be perceived by those other than the creator. The box confining those within, puppeteered by the being. The hands block those within from escaping, the hands of the creator";
    } else {
     document.getElementById('hello').textContent = "It pulls on it's chains";
    }
});
<!DOCTYPE html> 
<html>
  <head>
  
    
  </head>

  
  <style>
 div{

        background: orange;
    }  
</style>
  
  <body>
   
 
<div id= "chainbox" >
  
  <h2> <I id = "chain" > "It pulls on it's chains" </I>   </h2> 
  
  </div>

This is what i put into my website and it wont work. How do I fix it.

Failed Collision detection function

I have made a game using p5.js. The player is the white square and the walls are blue. I have made a collison detection function, but it is pretty spotty. Sometimes, it works fine, but other times there is a slight distance between the player and the wall. Can you please tell me what is going wrong? Any help would be greatly appreciated! Code is below:

function collide(a, b, dx, dy){
  var newx = a.x + dx * playerSpeed;
  var newy = a.y + dy * playerSpeed;
  if (newx < b.x + b.size && newx + a.size > b.x && newy < b.y + b.size && newy + a.size > b.y){
    return true;
  }
  return false;
}

For full code go to https://replit.com/@TonyWu4/Project

If you want examples on what is happening, Links to screenshots are below.

Working Fine

Not working

React – Creating a recursive comment system that moves the reply

Let me preface this question with my experience level. I have been trying to get into web development as a hobby, and as a result, I found my way to learning React. It’s been a fun experience trying to learn through trial and error. Usually, I have been following tutorials, but today, I have tried to do something a little more outside of my comfort zone.

I wish to create a comment system. All comments will be to the left side of the screen, displayed in an arbitrary manner. The user would select a comment from the left side, from where it will be displayed in full on the right side of the screen. The comment in the right side view will have a list of buttons. Each of those buttons opens up a reply to the parent comment. The child will be placed beside the parent.

Right now, I am only concerned with the logic of moving comments from the left view to the right view. In its current state, all the comments are shown in a single view, where clicking a reply button of a comment removes the reply from the main view, and places it directly beside the parent.

Given the limits of my understanding, I have worked out a half-solution. The major issue here is this bug: If a comment with no parent has two or more replies, opening all of them will cause the main list to not remove the replies from the main list, where they should be, and moved to the side of the parent. I tracked down what I believe to be the issue to the makeHidden function, or more specifically, the use of the backendComments useState. I guess that I am using it in a fundamentally wrong manner.

I apologize in advanced if I am not describing this question clearly. If my code is of no help, I would ask for a explanation on how you might tackle this problem, and please, any resources would be greatly appreciated.

CommentView.jsx

import {getComments} from '../mockDB/api'
import Comment from '../components/Comment'
import React from 'react'
import {useState, useEffect} from 'react'

function Threadview() {

    const [backendComments, setBackendComments] = useState([])
    const [cachedComments, setCachedComments] = useState([])

    var hiddenComments = [];

    const getReplies = (commentID) => {
        return cachedComments.filter(backendComment => backendComment.parentID === 
        commentID)
    }

    const makeHidden = (comment) => {

        hiddenComments.push(comment)

        var hiddenListIDs = [];
        hiddenComments.forEach((e) => hiddenListIDs.push(e.id))

        var filter = cachedComments.filter((backendComment) => 
        !hiddenListIDs.includes(backendComment.id))

        setBackendComments(filter)
    }

    useEffect(() => {
        getComments().then(data => {
            setBackendComments(data)
            setCachedComments(data)
        })
    }, [])

  return (
    <>
        {backendComments.length > 0 ?  backendComments.map((comment) =>
        <Comment key={comment.id} text={comment.text} replies={getReplies(comment.id)} 
        getReplies={getReplies} makeHidden={makeHidden}/>) : null}
    </>

}

Comment.jsx

import React from 'react'
import {useState, useEffect} from 'react'

function Comment({text, replies=[], getReplies, makeHidden}) {

    const [selectedReplies, setSelectedReplies] = useState([])

    const openReply= (comment) => {
        var newComment = <Comment key={comment.id} text={comment.text} replies= 
        {getReplies(comment.id)} getReplies={getReplies} makeHidden={makeHidden}/>

        var newList = [...selectedReplies, newComment]

        setSelectedReplies(newList)
        makeHidden(comment)

    return (
        <>
            {selectedReplies.length > 0 ? (
                <div className={styles['reply-container']}>
                    <div className={styles['reply']}>
                        {selectedReplies}
                    </div>
                </div>
            ) : (null)}

            {replies.length > 0 ? replies.map((comment) => <ReplyButton onClick={() => 
            openReply(comment)} key={comment.id} />) : null}
        </>
}

    

Total sum of a filtered table using vanilla JS

The only consideration for this question is, at the moment, I’m not using jQuery. Here’s the body of the page:

<body>
    <div class="container">
        <div class="card">
            <div class="card-header">
                Lista Pagos
            </div>
            <div class="card-body">
                <table id="emp-table" class="table">
                    <thead>
                        <tr>
                            <th>id</th>
                            <th col-index = 2>Persona
                            <select class="table-filter" onchange="filter_rows()">
                                <option value="all"></option>
                            </select>
                            </th>
                            <th col-index = 3>Servicio
                            <select class="table-filter" onchange="filter_rows()">
                                <option value="all"></option>
                            </select>
                            </th>
                            <th col-index = 4>Año
                            <select class="table-filter" onchange="filter_rows()">
                                <option value="all"></option>
                            </select>
                            </th>
                            <th col-index = 5>Mes
                            <select class="table-filter" onchange="filter_rows()">
                                <option value="all"></option>
                            </select>
                            </th>
                            <th>id Recibo</th>
                            <th>Valor</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td> 33 </td>
                            <td> David Camacho </td>
                            <td> Gas </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 7 </td>
                            <td> 10000 </td>
                        </tr>
                    
                        <tr>
                            <td> 32 </td>
                            <td> Héctor Camacho </td>
                            <td> Gas </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 7 </td>
                            <td> 15075 </td>
                        </tr>
                    
                        <tr>
                            <td> 30 </td>
                            <td> Héctor Camacho </td>
                            <td> Seguro exequial </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 6 </td>
                            <td> 11100 </td>
                        </tr>
                    
                        <tr>
                            <td> 29 </td>
                            <td> María Camacho </td>
                            <td> Seguro exequial </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 6 </td>
                            <td> 11100 </td>
                        </tr>
                    
                        <tr>
                            <td> 28 </td>
                            <td> Mateo León </td>
                            <td> Internet </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 1 </td>
                            <td> 20000 </td>
                        </tr>
                    
                        <tr>
                            <td> 27 </td>
                            <td> David Camacho </td>
                            <td> Internet </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 1 </td>
                            <td> 11600 </td>
                        </tr>
                    
                        <tr>
                            <td> 24 </td>
                            <td> Alba Camacho </td>
                            <td> Internet </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 1 </td>
                            <td> 11600 </td>
                        </tr>
                    
                        <tr>
                            <td> 23 </td>
                            <td> María Camacho </td>
                            <td> Internet </td>
                            <td> 2022 </td>
                            <td> 4 </td>
                            <td> 1 </td>
                            <td> 11600 </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <p id="sumV"></p>
    </div>
</body>

Inside the ‘<script>’ tag, here are the functions I used to make the select filters at the headers of each column work:

function getUniqueValuesFromColumn() {
    var unique_col_values_dict = {}
    allFilters = document.querySelectorAll(".table-filter")
    allFilters.forEach((filter_i) => {
        col_index = filter_i.parentElement.getAttribute("col-index");
        const rows = document.querySelectorAll("#emp-table > tbody > tr")
        rows.forEach((row) => {
            cell_value = row.querySelector("td:nth-child("+col_index+")").innerHTML;
            if (col_index in unique_col_values_dict) {
                if (unique_col_values_dict[col_index].includes(cell_value)) {
                    console.log("already exists");
                } else {
                    unique_col_values_dict[col_index].push(cell_value)
                }
            } else {
                unique_col_values_dict[col_index] = new Array(cell_value)
            }
        }); 
    });
    updateSelectOptions(unique_col_values_dict)
};

function updateSelectOptions(unique_col_values_dict) {
    allFilters = document.querySelectorAll(".table-filter")
    allFilters.forEach((filter_i) => {
        col_index = filter_i.parentElement.getAttribute('col-index')
        unique_col_values_dict[col_index].forEach((i) => {
            filter_i.innerHTML = filter_i.innerHTML + `n<option value="${i}">${i}</option>`
        });

    });
};

function filter_rows() {
    allFilters = document.querySelectorAll(".table-filter")
    var filter_value_dict = {}
    allFilters.forEach((filter_i) => {
        col_index = filter_i.parentElement.getAttribute('col-index')
        value = filter_i.value
        if (value != "all") {
            filter_value_dict[col_index] = value;
        }
    });
    var col_cell_value_dict = {};
    const rows = document.querySelectorAll("#emp-table tbody tr");
    rows.forEach((row) => {
        var display_row = true;
        allFilters.forEach((filter_i) => {
            col_index = filter_i.parentElement.getAttribute('col-index')
            col_cell_value_dict[col_index] = row.querySelector("td:nth-child(" + col_index+ ")").innerHTML
        })
        for (var col_i in filter_value_dict) {
            filter_value = filter_value_dict[col_i]
            row_cell_value = col_cell_value_dict[col_i]
            if (row_cell_value.indexOf(filter_value) == -1 && filter_value != "all") {
                display_row = false;
                break;
            }
        }
        if (display_row == true) {
            row.style.display = "table-row"
        } else {
            row.style.display = "none"
        }
    })
};

Next, I think here is where the problem relies, in the function I’m using to calculate the sum of the values under ‘Valor‘ column:

var t1 = document.getElementById("emp-table");
getSum();
function getSum() {
  var sumVal = 0;
  for(var i = 1; i < t1.rows.length; i++){
    sumVal = sumVal + parseInt(t1.rows[i].cells[6].innerHTML);
    document.getElementById("sumV").innerHTML = "Sum Value = "+sumVal;
  }
};

And finally, the ‘onload’ part to update the content:

window.onload = () => {
    console.log(document.querySelector("#emp-table > tbody > tr:nth-child(1) > td:nth-child(2) ").innerHTML);
};

getUniqueValuesFromColumn()

So, at the moment, whenever I load the page, the <span> tag already has the total amount if we consider all rows. But, whenever I filter the table, the value there doesn’t change. At first, I tried to do it with a button using onclick, but every time I clicked it, it changed from the total value to ‘undefined’. That’s why I removed that button, and I’m considering to update the content in the <span> tag with the onload segment of my code, but I’ve been unable to achieve it so far.

Any help is greatly appreciated, cheers!

Problems using post request

I’m having problems trying to use a POST request in axios.
I need to send an object to my backend, but it receives predefined values ​​inside my function, so I can’t send all my data.
I tried in different ways and got different messages but I still couldn’t find my error.

export function createUsers(user: userApi) {
  user.pin = '001'
  user.customFields = []  
  //@ts-ignore
  user.admission_at = selectedDate.value

  return axios.post('',{
    ...user,
    admission_at: dateBr(user.admission_at)
  })
}

In this first attempt when I send data, it ends up sending only the pre-defined values:

enter image description here

On the second try I only modified my return, but this time I send my object and it ignored my predefined values, like the “pin” for example. That way I didn’t know how to format my date either, using “dateBr”. I believe that the best way to send is the first one, but I need all the data

enter image description here

export function createUsers(user: userApi) {
  user.pin = '001'
  user.customFields = []  
  //@ts-ignore
  user.admission_at = selectedDate.value
    
 return axios.post('', user)
}

How to test TextInput in react-native with @testing-library/reat-native?

I’m trying to test a TextInput by checking its value after entering a string, but it’s not working. Any help would be appreciated.

Here’s the code:

import React from 'react'
import { TextInput } from 'react-native'
import { fireEvent, render } from "@testing-library/react-native"

test('<TextInput/>, () => {
  const { getByTestId } = render( <TextInput testID="input" /> );
  const input = getByTestId("input");
  fireEvent.changeText(input, "123");
  expect(input.value).toBe("123");
})

The test fails with the message:

Expected: "123"
Received: undefined