Why does VS code say there is an error with my object property?

I was testing some code that utilizes objects in TypeScript and noticed that my IDE’s IntelliSense was throwing an error for a new property I was trying to add. It states that the property “text” does not exist, here is my code:

// create new object
var thing : Object = new Object();

// Do things
thing.text = "This is a test.";
console.log(thing.text);


// dereference the object
thing = null;

The error is highlighted on the line(s):

thing.text = "This is a test.";
console.log(thing.text);

Why does VS code list this as an error when this is perfectly acceptable code and behavior in JavaScript? Here is the error screenshot from my editor:
Error

Vanta.js not reloading after GSAP & Barba JS transition

Ok so I got a Vanta.js background running in my <main> which looks awesome. Then I introduced a page transition using Barba and GSAP for animations, which are working fine too. But after going back to my index I found that VantaJS isn’t loading again. There are very few questions about Barba and even less answered correctly.

Here’s what I’ve tried until now:

  • Use window.onload with appendChild to add the vanta libraries each time.
  • Use Barba hooks to reload the libraries on “after” hook.
  • Send all scripts to the bottom of my html in correct order.

Here are some SO questions I’ve used as example:

How to reinit custom js files between pages (Barba.js)?

Scripts are not loading after the page transition in Barba.jS

JS content not working after a page transition using Barba.JS

No luck implementing any of these.

I’m open to other transition libraries if you think that Barba is the problem definitely.
Thanks in advance.

Group by month and year is in out of order

This question is an extention of this question here. Underscore js group by each month on each year in single level

The code which i am using is here.

        const months = [
            'January','February','March','April','May','June','July','August','September','October','November','December'
        ]
        const result = flashMessage.reduce((res:any, item:any) => {
            const date = new Date(item.created_at)
            const year = date.getFullYear();
            const month = months[date.getMonth()];
            const existingYear=res[`${month} ${year}`] ||[]; 
            const updated  = [...(existingYear[month] || []), item]
            const returnItem = {
                title:item.title,
                user_message:item.user_message,
                created_at:item.created_at
            };
            res[`${month} ${year}`] = [...existingYear,returnItem]
            return res
        }, {});

The above code is producing expected result but it is in out of order here is the result of the above code.
[![enter image description here][1]][1]

I want the result is in order. The order which i wanted is shown below.

March 2022

February 2022

January 2022

March 2021

February 2021

January 2021

So on how can i do that?
[1]: https://i.stack.imgur.com/BS9ZS.png

Select multiple dates in the mutiple date selelect picker

Im using laravel. I have saved multiple dates using multiple date selector. so now i need to select those saved values in that date picked when loading screen again.
my date picker created like this.


<input type="text" id="closed_dates" name="closed_dates" class="form-control date"/>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>

<script>
        $('#closed_dates').datepicker({
            multidate: true
        });
</script>

it has saved value in the database like this format,

03/01/2022,03/02/2022,03/09/2022,03/10/2022,03/11/2022

so when loading my page, values pass from the controller.
i need to select those dates in that date picker on the page load. how can i do it?

MUI ToggleButton set selected background-colour dynamically

const StyledToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({
    "&.Mui-selected, &.Mui-selected:hover": {
        backgroundColor: selectedColor,
    }
}));
const FilterTeam = (props) => {
  const [view, setView] = useState(1);
  const handleChange = (event: any, nextView: any) => {
    setView(nextView);
  };

  return (
   <ToggleButtonGroup
    orientation="horizontal"
    value={view}
    exclusive
    onChange={handleChange}
   >
    { Object.values(teams).map((teamObject: any, index) =>
     <StyledToggleButton
      key={teamObject.team}
      className={classes.toggleButton}
      value={teamObject.team}
      selectedColor={teamObject.colorTheme}
     >
      <img className={classes.teamLogo}
        alt="team logo" src={teamObject.logo} />
     </StyledToggleButton>
    )}
   </ToggleButtonGroup>
  );
}

export default FilterTeam

I keep getting:Warning: React does not recognize the selectedColorprop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercaseselectedcolor instead. If you accidentally passed it from a parent component, remove it from the DOM element.. I have gone over a couple sandbox which implement the same but I am trying it on typescript so I am not sure how it converts.
I have referred to https://codesandbox.io/s/69707814-set-selected-color-of-toggle-button-group-mui-5l5lh?file=/demo.js

Export a Monkey Patch library and Import it into a separate file in Javascript

I’m working in WebDriverIO w/Mocha, and there’s some monkey patches I’ve written to make my code easier to read. Things like:

  • Object.prototype.findEntries(...arr) for getting a subset of Object.entries(),
  • String.prototype.padding(int), adding spacing to the right of a string,
  • Array.prototype.sortByKey(key) to sort an array of similar objects by the value of a common key, and
  • Array.prototype.last(), the classic.

Since I have many spec files with even more tests, I’d like to have a MonkeyPatchLib.js in my project that I can import into my spec files, so I can call these custom functions when needed:

myTest.js:

import { all } from './MonkeyPatchLib.js' // <- line in question

describe('My First Spec File', async() => {
    it('First Test', async() => {
        let myArr=[1,2,3]
        console.log(myArr.last())
    })
})

I’ve screwed around with module.exports=[func1(){...},func2(){...}] to no avail. I’m aware that I can simply create custom classes (a la the solution to this question) and export those, but that would require an annoying refactor of my codebase. How should I format the library, and how would one import said library?

How to initiate ojet menu from javascript

We are using below function in java script to trigger oj-dialog and its working fine.

else if(operation === "fmethod"){
            
            var popup = document.getElementById("fPopUp");
            if (!popup.isOpen()) {
                popup.open();
            }
            return;

But when I am using the same function to trigger oj-menu or any other oj element we are getting “popup.isOpen is not a funtion” error.

Can someone let me know what should be the equivalent syntax of javascript to trigger or start oj-menu.

Why is JS redis looping more times after succesful write?

I have the following logic for reading and writing redis state

export async function updateRedis() {
let stateName = 'stateName'
try {
    let isSuccess = false
    while (!isSuccess) {
        try {
            await redis
                .watch(stateName, function (err) {
                    if (err) {
                        logger.error(`Error in watch state: ${err}`)
                    }
                    redis.get(stateName, function (err, result) {
                        if (err) {
                            logger.error(`Error in get state: ${err}`)
                        }

                        let state = JSON.parse(result)
                        // do some processing
                        redis.multi()
                            .set(stateName, JSON.stringify(state))
                            .exec(function (err, result) {
                                if (err) {
                                    logger.error(`Error in set state: ${err}`)
                                }
                                if (result != null) {
                                    isSuccess = true
                                }
                            })
                        console.log(`isSuccess for ${stateName} `, isSuccess)
                    })
                })
        } catch (e) {
            logger.error(`Error: ${e}`)
        }
    }
} catch (e) {
    logger.error(`Error: ${e}`)
}
return Promise.resolve(true)

}

This will print out

"isSuccess for stateName false"
"isSuccess for stateName true"
"isSuccess for stateName true"

So after the flag changes to true, it will continue for more loops. Sometimes it does more than just once.

Am I doing something wrong?

Material UI – Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

how are you?

I have a React project with Webpack and Babel, and i’m trying to add Material UI (https://mui.com/) components, however, when i import a MUI component into my project i get the next error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

A workaround i found is to add the “.default” import, but i don’t understand why i’m not able to just import it the traditional way.

Here’s a test component code that produces the error:

const React = require("react");
const Button = require("@mui/material/Button");

const Navbar = () => {
  return <Button variant="contained">Contained</Button>;
};

module.exports = Navbar;

And here’s my .babelrc and webpack.config code:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  output: {
    path: path.join(__dirname, "/dist"),
    filename: "index.bundle.js",
  },
  devServer: {
    port: 8443,
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /.scss$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({ template: "./src/index.html" }),
    new MiniCssExtractPlugin(),
  ],
};

Does anyone know what i’m doing wrong? I know it might be silly, but i should be able to just import these components the “normal” way as stated in the MUI documentation, instead, i have to import them using the “.default” way.

Thanks in advance, sorry for my bad english.

Method “getChampionName” has type “undefined” in the component definition. Did you reference the function correctly?

im trying to use this function (src/api/)

function getChampionName(champId) {
  axios.get('http://ddragon.leagueoflegends.com/cdn/12.5.1/data/en_US/champion.json')
    .then(({ data }) => {
      let list = data
      let championList = list.data
      for (var i in championList) {
        if (championList[i].key == champId) {
          return championList[i].id
        }
      }
    })
    .catch((err) => console.log(err))
}

export {getChampionName}

in this component (src/components/)

<template>
  <div class="w-72">
    <header class="rounded-tl-lg rounded-tr-lg bg-slate-400 p-0.5">
      <p>Champion's Mastery</p>
    </header>
    <ul class="grid gap-1 rounded-bl-lg rounded-br-lg bg-slate-50 p-0.5">
      <li v-for="champ in masteryData.slice(0,10)" :key="champ.championId">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <img src="https://ddragon.leagueoflegends.com/cdn/12.5.1/img/champion/Karma.png" alt="" class="rounded-lg h-14 w-14">
            <div>
              <p class="font-medium text-center">{{ getChampionName(champ.championId) }}</p>
              <p>Level {{ champ.championLevel }}</p>
            </div>
          </div>
          <p class="text-2xl font-medium">{{ champ.championPoints }} Pts</p>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import getChampionName from '@/api/search'

export default{
  name: 'MasteryInfo',
  props: [
    'masteryData'
  ],
  methods: {
    getChampionName
  }
}
</script>

But im getting this error “Method “getChampionName” has type “undefined” in the component definition.” and dont know what it means

Unzipping the folder but getting this error

Unzipping the folder but getting this error.
TypeError [ERR_INVALID_ARG_VALUE]: The argument ‘path’ must be a string or Uint8Array without null bytes. Received “PKx03x04x14x00x00x00x00x00]pkTx00x00x00x00x00x00x00x00x00x00x00x00x0Ex00x00x00Documentation/PKx03x04…

            decompress(data.data.toString('utf8'), 'output', {
              plugins: [
                  decompressUnzip()
              ]
          }).then(() => {
              console.log('Files decompressed');
          });

(REACT.JS)How to increment a data in my component

class Personne extends React.Component {
// constructor(props){
//     super(props);
// }
birthdayHandler = () => {
    let Age = this.props.age;
    let ageToNumber = parseInt(Age);
}

render(){
    return(
       <Fragment>
         <div className={classes.maintitle}>
            <h1 style={Name}> {this.props.name}</h1>
            <div> Job : {this.props.job}</div>
            <AgePersonne age={this.props.age}/>
            <div> Sexe : <strong style={sex}>{this.props.sexe ? "Homme" : "Femme"}</strong></div>
            <button onClick={(event) => this.birthdayHandler(event)} style={Button}>Birthday</button>
         </div>
       </Fragment>
    )
}

}

I would like to increment the age of the person by clicking on the button.

the AgePersonne component looks just like this :

const agePersonne = (props) => {
    const now = new Date();
    const year = now.getFullYear();
    return(
        <div>Age : {props.age} - année de naissance :{year - props.age -1}</div>
    )
};`

I did it already in a parent component with a button, but it increments all of my person’s age.
The APP component looks like this :

class app extends Component {

state = {
  personne: [
    {name: "Andy GARCIA", age: "28", job:"Web Dev", sexe: true},
    {name: "Sylvie MOISAN", age: "60", job:"nurse", sexe: false},
    {name: "Benjamin BARIOHAY", age: "27", job:"Web Dev", sexe: true},
    {name: "Galina RAZLIVANOVA", age: "29", job:"Web Security consultant", sexe: false},
    {name: "Maxime GIRARDEAU", age: "28", job:"Sailer", sexe: true},
  ]
}
  render() {
      return (
        <Fragment>
          <Horloge />
          <Personne {...this.state.personne[0]}/>
          <Personne {...this.state.personne[1]}/>
          <Personne {...this.state.personne[2]}/>
          <Personne {...this.state.personne[3]}/>
          <Personne {...this.state.personne[4]}/>
        </Fragment>
      )
  }

}

could you help me please ? I’m really lost, thank you

Positioning options menu directly under highlighted text

I’m trying to show the user a pop up menu with some options if they highlight any text in the browser. I want the menu to be displayed directly under the highlighted text.

I am currently using getBoundingClientRect() on the range of the text. Passing the object to the menu and using the coordinates to set the positioning.

function doSomethingWithSelectedText() {
    let selectedText = getSelectedText();
    let sel;
    if (selectedText && selectedText.indexOf(' ') === -1) {
        console.log('SELECTED TEXT =>', selectedText)
        sel = window.getSelection();
        if (sel.rangeCount) {
            let range = sel.getRangeAt(0);
            let coords = range.getBoundingClientRect()
            setTimeout(() => { handleShowMenu(coords) }, 800)
        }

    }
}
const handleShowMenu = (coords) => {

    menu.style.display = 'block'
    menu.style.left = coords.x + 'px'
    menu.style.top = coords.y + 'px'
}

During some highlighting tests of various text elements I notice:

  • The menu is positioned right under the <p> tags perfectly as to my desire.
  • The menu is positioned under the <h3> but closer to the top, almost overlapping the text.
  • The menu is positioned right under the <h1> but now partially overlapping the bottom of the text.

Any reason for this behavior, as well as a possible solution? thanks.