Redux and Route Issue on “Type ‘{}’ is missing the following properties from type”

I got stuck on routing some code with redux.

// featureSlice.js

const featuresSlice = createSlice({
  name: "features",
  initialState: {
    explore: {
      page: 1,
      features: [],
    },
    favs: [],
  },
  reducers: {
    setExploreFeatures(state, action) {
      const { explore } = state;
      const { payload } = action;
      payload.features.forEach(payloadFeature => {
        const exists = explore.features.find(
          savedFeature => savedFeature.id === payloadFeature.id
        );
        if (!exists) {
          explore.features.push(payloadFeature);
        }
      });
      state.explore.page = payload.page;
    },
    increasePage(state, action) {
      state.explore.page += 1;
    },
    setFavs(state, action) {
      state.favs = action.payload;
    },
  },
});

export const { setExploreFeatures, increasePage, setFavs } =
  featuresSlice.actions;

export const getFeatures = () => async dispatch => {
  try {
    const {
      data: { results },
      // data
    } = await api.features();
    console.log(results);
    dispatch(
      setExploreFeatures({
        rooms: results,
        page: 1,
      })
    );
  } catch (e) {
    console.warn(e);
  }
};

export default featuresSlice.reducer;

// index.js

import { connect } from "react-redux";
import { getFeatures, increasePage } from "../../redux/featuresSlice";
import ExploreContainer from "./ExploreContainer";

function mapDispatchToProps(dispatch) {
  return {
    getFeaturesWith: page => dispatch(getFeatures(page)),
    increasePageWith: () => dispatch(increasePage()),
  };
}

function mapStateToProps(state) {
  return state.featuresReducer.explore;
}

export default connect(mapStateToProps, mapDispatchToProps)(ExploreContainer);

and

\ ExploreContainer.js 

export const ExploreContainer = ({
  getFeaturesWith,
  features,
  increasePageWith,
}) => {
  useEffect(() => {
    getFeaturesWith();
  }, []);
  return (
    <div className="h-screen flex items-center justify-center bg-gray-800">
      <div className="bg-white w-full max-w-lg pt-10 pb-7 rounded-lg text-center">
        <h3 className="text-2xl text-gray-800">Log In</h3>
      </div>
    </div>
  );

and i am trying to route this code with router below

// router.tsx 

const ClientRoutes = [
  <Route key={6} path="/happy" element={<ExploreContainer />
];

export const LoggedInRouter = () => {
  return (
    <div>
      <BrowserRouter>
        <Header />
        <Routes>
          {ClientRoutes}
          {/* <Route>
                        <NotFound />
                    </Route> */}
        </Routes>
      </BrowserRouter>
    </div>
  );
};

But it comes out with an error saying ‘ Type ‘{}’ is missing the following properties from type ‘{ getFeaturesWith: any; features: any; increasePageWith: any; }’: getFeaturesWith, features, increasePageWith

Is there any way I can figure this out?
Plz help me thx…

Discord.js Ping Pong command with cooldown

I’m very new to coding so it’s probably horrible. Here’s the code

    let userCooldown = {};

client.on("message", message => {
    if (message.content.includes('ping'))
    if (userCooldown[message.author.id]) {
        userCooldown[message.author.id] = false;
        message.reply('Pong');
        setTimeout(() => {
            userCooldown[message.author.id] = true;
        }, 5000) // 5 sec
    }
})

the plan would be for the bot not to respond to the message for 5 seconds until it’s written again

Site elements only arrange properly after tablet reoriented

I have a 2×3 grid, showing images on the site. The site is responsive, so it can realign to 3×2, or to only show 1 image in a row. The problem is, when I start it on a tablet it shows it as a 3×2 grid for some reason. if I orient it to be vertical, it shows 1 image per row, then I reorient it horizontally, the images align into a 2×3 grid properly as they should with that resolution.

Why do I have to reorient the tablet to make the site show the elements properly?
Here is the picture before reorienting and after:
https://i.stack.imgur.com/qR35M.jpg
(I am sorry about the image quality, it’s not from me).

Here are the snippets:

@charset "utf-8";

/* 
@media (min-height: 600px) {
    * {
      font-size: 5vh;
    }
} */

html, body, button {
  background-color: #353535;
  color : #FCFCFC;
  font-family: 'Quicksand';
  font-weight : 700;
  font-size : 4.5vh;
  border-width: 0px;
  border: none;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  padding: 0px;
}


/* .vertical-center {
    margin: 0;
    position: absolute;
    top: 50%;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
} */

.wrap {
    width:100%;
    height: 100%;
    display:table;
}

.tr { 
    display:table-row;
    /* justify-content: center; */
}

.tc { 
    display:table-cell;
    padding-left: 15%;
    padding-right: 15%;   
    padding-top: 1%;
    padding-bottom: 1%;   
}

.header {
    height: 100%;
    padding-top: 1%;
    padding-left: 12%;
    padding-right: 12%;
}

.mid {
    height: 78%;
}

.footer {
    height: 13%;
    padding-left: 15%;
}

#bigscreen {
    height: 90%;
    /* padding: 2%; */
    border: 15px solid #6D9E18;
    border-radius: 1rem;
    position: relative;
    
}
  
.cards {
    /* margin: 0 auto; */
    display: grid;
    grid-gap: 1rem;
    grid-template-columns: repeat(auto-fit, minmax(7.8rem, 0.3fr));
    /* align-content: center;
    justify-content: center; */
}  


.card {
    border-radius: 1rem;
    border-width: 0px;
    border: none;
    background: #545553;
    width: 7.8rem;
    height: 7.8rem;
    position: relative;
    box-sizing: border-box;
}

.svgicon img, .svgicon svg {
    position: relative;
    height: 1em;
    width: auto;
    top: 5px;
    left: 5px;
    padding: 15px;
    color:currentColor;
}

.bigicon {
    height: 3em;
    width: auto;
}

.button {
    width: 7.8rem;
    border-radius: 1rem;
    background-color: white;
    color: black;
    justify-content: center;
    align-items: center;
}

.small-gray {
    height: 2em;
    display: flex;
    background:gray;
    color: white;
}

.button-big {
    height: 7.8rem;
    display: inline-block;
    text-align: center;
    vertical-align: middle;
}

.button-small {
    height: 2em;
    display: flex;
}

.button-small:focus {
    height: 7.8rem;
    display: inline-block;
    text-align: center;
    vertical-align: middle;
}

.caption {
    display: block;
}

img.contact-image {
    height: 100%; 
    width: 100%; 
    max-width: 7.8rem; 
    max-height: 7.8rem;
    border-radius: 1rem;
    border: none;
}

.contact-text {
    background-color: white;
    color: black;
    position: absolute;
    padding-top: 0.3rem;
    top: 75%;
    height: 25%; 
    width: 100%;
    text-align: center; 
    vertical-align: middle;
    border-radius: 0px 0px 1rem 1rem;
}


.contact-text:focus {
    background-color:  #6D9E18;
    color: white;
}

.focusable {
    outline: 0;
}
  
.focusable:focus {
    opacity: 1;
    /* border-color: #6D9E18;
    border-width: 4px; */
    background-color: #6D9E18;
    color: white;
}
  

/* Designing dialog box */
#container { 
    display: none; 
    background-color: #FCFCFC; 
/*    background-color: #6D9E18; */
    height: 50%;
    width: 50%;
    /* color: #0000000;  */
    position: absolute; 
    border-radius: 1rem; 
/*          left: 50%; 
    margin-left: -160px; */
    padding: 16px 8px 8px; 
    box-sizing: border-box; 
} 

/* Designing dialog box's okay buttun */
#container .yes { 
    background-color: #5c940d; 
    display: inline-block; 
    border-radius: 1rem; 
    border: none;
    padding: 5px; 
    margin-right: 10px; 
    text-align: center; 
    width: 60px; 
    float: none; 
} 

#container .no { 
    background-color: #22b8cf; 
    display: inline-block; 
    border-radius: 1rem;
    border: none;
    padding: 5px; 
    margin-right: 10px; 
    text-align: center; 
    width: 95px; 
    float: none; 
} 
<div class="wrap">
        <div class="tr">
             <div class="header">
                    <p style="text-align:left;margin:0%">
                    thing
                    <span style="float:right;" id="datetime">
                        <span id="datetime"></span>
                    </span>
                </p>
            </div>
        </div>
        <div class="tr mid">
            <div id="mymiddle" class="tc">
                <!-- Big screen -->
                <!-- <div id="bigscreen">
                    Ide jön a video...
                </div>     -->
                
                <div class="cards">
                    <!-- Div 1 -->
                    <div id="mid_1" class="card">
                        <!-- Robert  -->
                        <button id="button_1" class="card" onclick="SelectUser(this)">
                            <img class="contact-image" src="images/Robert.jpeg" alt="Robert"> 
                            <div id="ctext_1" class="contact-text focusable">Robert </div> 
                        </button>
                    </div>
            
                    <!-- Div 2 -->
                    <div id="mid_2" class="card">
                        <!-- Anna -->
                        <button id="button_2" class="card" onclick="SelectUser(this)">
                            <img class="contact-image" src="images/Anna.jpeg" alt="Anna"> 
                            <div id="ctext_2" class="contact-text focusable">Anna </div> 
                        </button>
                    </div>
            
                    <!-- Div 3 -->
                    <div id="mid_3" class="card">
                    </div>
            
                    <!-- Div 4 -->
                    <div id="mid_4" class="card">
                        <!-- <button id="buttonvideo" class="button focusable button-small" onclick="startVideo()">     -->
                        <button id="buttonvideo" class="button button-small" onclick="startVideo()">    
                                <span class="icon svgicon">
                                <img src="icon/videohivas.fekete-12.svg" alt="Videóhivás"> 
                            </span>
                            
                        </button>
                    </div>
            
                    <!-- Div 5 -->
                    <div id="mid_5" class="card">
                        <button id="buttonvoice" class="button button-small" onclick="startVoice()">    
                            <span class="icon svgicon">
                                <img src="icon/hanguzenet.fekete.svg" alt="Hangüzenet"> 
                            </span>
                            
                        </button>
                    </div>
            
                    <!-- Div 6 -->
                    <div id="mid_6" class="card">
                        <button id="buttonmessage" class="button button-small" onclick="startMessage()">    
                            <span class="icon svgicon">
                                <img src="icon/beerkezo.fekete-12.svg" alt="Üzenet"> 
                            </span>
                            
                        </button>
                    </div>
            
                </div>                              

            </div>
        </div>

Exception: The number of rows in the range must be at least 1

I’m trying to run this code that will get the first 7 columns from sheet1 in spreadsheet1 and paste them in sheet2 in spreadsheet2, but im keep getting this error which I dont know why.

Exception: The number of rows in the range must be at least 1. 6th line

function MoveCode(){
  const ss1 = SpreadsheetApp.getActive();
  const ss2 = SpreadsheetApp.openById("1zU__ccPIMst54whmyrbmRnDRRjOtQBFPzXhw6NsFqpU");//or url whatever
  const ssh = ss1.getSheetByName('Sheet1');
  const dsh = ss2.getSheetByName('Sourcing');
  const vs = ssh.getRange(2,1,ssh.getLastRow() - 1,7).getValues();
  dsh.getRange(2,1,vs.length,vs[0].length).setValues(vs);
}

test3 is the spreadsheet that i want to paste the data to
from.

If you need anymore explanation please let me know

enter image description here

How do I correctly find a value in an object from an array, by matching it to another array with the values

So I have an array of values which I need to find:

const values = [ 'v4', 'w1']

And there is the array of objects where I need to look into:

const nodes = [
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v1"
                },
                {
                    "name": "Key2",
                    "value": "w1"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v1"
                },
                {
                    "name": "Key2",
                    "value": "w2"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v2"
                },
                {
                    "name": "Key2",
                    "value": "w1"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v2"
                },
                {
                    "name": "Key2",
                    "value": "w2"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v3"
                },
                {
                    "name": "Key2",
                    "value": "w1"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v3"
                },
                {
                    "name": "Key2",
                    "value": "w2"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v4"
                },
                {
                    "name": "Key2",
                    "value": "w1"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v4"
                },
                {
                    "name": "Key2",
                    "value": "w2"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v5"
                },
                {
                    "name": "Key2",
                    "value": "w1"
                }
            ]
        }
    },
    {
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v5"
                },
                {
                    "name": "Key2",
                    "value": "w2"
                }
            ]
        }
    }
]

And I basically need to find which is the node that matches the values array (in this example, the result should be nodes[6]

{
        "node": {
            "options": [
                {
                    "name": "Key1",
                    "value": "v4"
                },
                {
                    "name": "Key2",
                    "value": "w1"
                }
            ]
        }
    },

values array will always have the length of node.options, but one of the values can be undefined in which case the first occurrence of the defined value should be returned.

e.g. values = [ undefined, 'w1'] -> nodes[0]

I managed to do something like

const result = nodes.find(
        (node) =>
          options[0].value === values[0] &&
          options[1].value === values[1]
      );

But his won’t work if options has length different than 2.

Some other things I tried: (but seem to no be working)

nodes.find((node) => node.options.find(item => {
        values.map(opt => opt === item.value)
      }))

nodes.find((node) => node.options.filter(item => {
    return values.includes(item.value)
  }))

Why i can’t generate 20 person in people? [duplicate]

const fs = require('fs');

const genders = ['male', 'female'];
const maleNames = ['Adrian', 'Rafał', 'Michał', 'Sebastian'];
const femaleNames = ['Aleksandra', 'Magdalena', 'Klaudia', 'Oliwia'];
const lastNames = ['Nowak', 'Kowalski', 'Szymański', 'Lewandowski'];

function randChoice(arr){
  return Math.random(arr);
}

const people = [];

for (let i=0; i<20; i++) {
  function Person(gender, firstName, lastName, age) {
    this.gender = gender;
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  let person = new Person(gender, firstName, lastName, age);
  const gender = randChoice(genders);
  const firstName = function(name){
    if (gender = 'male'){
      return randChoice(maleNames);
    }
    else {
      return randChoice(femaleNames);
    }
  }
  const lastName = Math.random(lastNames);
  const age = function getRandomInt(min, max) {
    min = Math.ceil(0);
    max = Math.floor(100);
    return Math.floor(Math.random() * (max - min)) + min;
  }
  return people.push(person);
}
console.log('People', people);

I try create 20 random person and add to people, but when i open console and type ‘node app.js’ I see nothing. Where do i go wrong. Why i can’t generate 20 person in people?

how to save toogle class with localstorage. so can someone check what’s wrong with this code

if( localStorage.getItem("color") == "black" ) {
  
{
   var element = document.getElementById("body");
   element.classList.toggle("bdark");
}
{
   var element = document.getElementById("theader");
   element.classList.toggle("hdark");
}
{
   var element = document.getElementById("sh");
   element.classList.toggle("shh");
}
       
}

function myFunction() {
 
{
   var element = document.getElementById("body");
   element.classList.toggle("bdark");
}
{
   var element = document.getElementById("theader");
   element.classList.toggle("hdark");
}
{
   var element = document.getElementById("sh");
   element.classList.toggle("shh");
}
     var hs = document.getElementById("hs");
     
     var color;
     if(localStorage.getItem("color") == "black") {
       color = "black";
       
     localStorage.setItem("color",color)

}
.bdark {
  background-color: #333;
  color: white;
}

.hdark {
  background-color: black;
  color: white;
}

.shh {
  display: none;
}

.hs {
  display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">

<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>

<button id="button" onclick="myFunction()">Try it</button>

<div id="aaas">
 <div id="sh" class="sh">&#9790;</div>
 <div id="hs" class="hs">&#9728;</div>
</div>

</body>
</html>

i want this code to onclick toggle class and when i refresh the page those toggled class remain same as they were before reloading the page with localstorage. so can someone check what’s wrong with this code. help me with something similar/alternative to this one. thanks for reading this.

Details:-

i want this code to work as (onclick class change + saved with cokies/localstorage/or anything) so whenever i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same.

Problem with YouTube Data API to retrieve user’s channel Id

Good mornirg lads,
I am trying to implement a React – Node js application that authenticates the user with Google and then retrieve its YouTube channel Id with google apis. I’m new to Google APIs, so I need some help to make this code works. The authentication with Google perfectly works, but I have a lot of difficulties in making the request to retrieve the channel id.

This is the code to focus in the React authentication component implemented with react-google-login:

<GoogleLogin
    clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
    buttonText="Log in with Google"
    onSuccess={handleGoogleLoginSuccess}
    onFailure={handleGoogleLoginFailure}
    cookiePolicy={'single_host_origin'}
    scope='https://www.googleapis.com/auth/youtube.readonly'
/>

  const handleGoogleLoginSuccess = (googleData) => {
        //The token id is in googleData.tokenId
        console.log(googleData);
        axios.post('auth/googleLogin', {
            token: googleData.tokenId,
            access_token: googleData.accessToken
        }).then(response => {
            //Login success
            if(response.data.loginStatus === 'ok') {
                setLoginMessage(''); //Reset message
                const user = response.data.user;
                console.log(user.email + " " + user.firstName + " " + user.lastName)
                registerUser(user); //Register user in the context
                //console.log(currentUser.email + " " + currentUser.firstName + " " + currentUser.lastName)
                localStorage.setItem('user', JSON.stringify(user)); //Push user in the storage
                history.push('/home'); //Redirect to home page
            }else{ //Login fail
                //Set error messages.
                const message = response.data.message;
                setLoginMessage(message);
            }
        });
    }

    const handleGoogleLoginFailure = () => {
        setLoginMessage("Impossible to login with Google at the moment. Please retry later.")
    }

While the end point in the express server is:

router.post('/googleLogin', async (req, res) => {
const { token, accessToken } = req.body;

const ticket = await client.verifyIdToken({
    idToken: token,
    audience: process.env.CLIENT_ID
});
const {email, given_name, family_name} = ticket.getPayload();

const { OAuth2 } = google.auth;
const oauth2Client = new OAuth2();

oauth2Client.setCredentials({ access_token: accessToken });

var service = google.youtube({
    version: 'v3',
    auth: oauth2Client,
});
service.channels.list({
    key: process.env.GOOGLE_API_KEY,
    auth: client,
    mine: true,
    part: 'snippet',
}, (err, response) => {
    if(err) {
        console.log(err);
        return;
    }
    var channels = response.data.items;
    console.log(channels);
});

const [user, created] = await User.upsert({
    email: email,
    firstName: given_name,
    lastName: family_name,
    youtubeChannelId: 'TODO'
});

if(user) {
    const accessToken = createTokens(user);
    res.cookie("access-token", accessToken, { 
        maxAge: 60 * 60 * 24 * 1000, //one day
        httpOnly: true
    });
    return res.json({ 
        loginStatus: 'ok',
        user: user 
    });
}else{
    console.log("Error in login with Google");
}

});

I’m getting the error:
Error: No access, refresh token, API key or refresh handler callback is set.

Some ideas?

loop in js, but wait till current iteration is done, then get to next

My goal is to execute a function that can print number 1-4; But in 1s intervals (and I don’t want to use setInterval). I’ve been trying and what I could do was to print all the elements in an array after one second delay. here’s the code :

const wait = async (number) => {
  return new Promise(async(resolve)=>{
    setTimeout(async()=>{
      resolve();
    },number);
  })
}

const listElement = document.getElementById("list");

[1,2,3,4].map((num)=>{
  const newListItemElement = document.createElement("li");
  newListItemElement.innerHTML = num;
  wait(1000).then(()=>{
    console.log(num);
    listElement.appendChild(newListItemElement);
  })
})
<html>
<body>
  <h3>list</h3>
  <ul id="list">
  </ul>
</body>
</html>

What I want this to do is to wait a second and print 1 then wait a second and print 2 and so on. The code I added in the snippet is making all the numbers appear together at once and this is because map function goes on even if the current iteration isn’t done yet.

Нужно создать функцию которая будет принимать параметром тот массив который отфильтрован [closed]

Нужно создать функцию которая будет принимать параметром тот массив который отфильтрован. Дальше эта функция будет возвращать объект json адаптивной карточки, а в этом объекте адаптивной карточки перебираешь массив и отрисовывашь текстовые блоки
Эту функцию вызываешь когда нажимаешь на кнопку в боте, получаешь карточку которая тебе вернула функцию и отправляешь ее в бот.

axios.get("url(guid)items", { 
       headers: {
         'Authorization': 'Bearer 'token' '
       }
     })
       .then((res) => {
         console.log(res);
         let today = new Date();
         const tmp = res.data.value.filter(item => moment(item.field_4).format('MM') === moment(today).format('MM'));
         console.log(tmp);
       })

Можете подсказать как создать такую функцию

How to handle a variable that might be an array or not in javascript?

I need to take an argument that is either an array of one type or the type on its own:

const foo = typeOrArrayOfType => myFunction([...typeOrArrayOfType, oneDefault]);

However if I do this:

const anArray = ['oneItem', 'twoItem'];
const notAnArray = 'oneItem';
const nonIterator = 300;
const oneDefault = 20;

const foo = typeOrArrayOfType => console.log([...typeOrArrayOfType, oneDefault]);

foo(anArray) // prints array items
foo(notAnArray) // spreads the string
foo(nonIterator) // error

It either works, spreads the string into characters or breaks entirely.

How can I flexibly take arguments that may or may not be an array?

ReactJS – Going back in nested routes with Reacter Router Dom V6

My initial page is

http://localhost:3000/home

With a navigation bar I go to a list of products in:

http://localhost:3000/products/all/

When I click a product in the list I go to:

 http://localhost:3000/products/banana/

Now if I click Back on the browser or if I make a button with the new useNavigate and try to do navigate(-1) I go to /home in both examples.

How can I make it so I go to /products/all/ with useNavigate and hopefully I can do change the browser interaction too?