How to work with upcoming events without year

I have a React native application with events where I have event dates in ISO format. I need to work with events on a yearly repeating basis. Events include dates like birthdays and also yearly events. I need to display upcoming events for the rest of the current year then display events for the next year. How to work with events without a year and sort by current date?

events.sort((a, b) => {
    const today = new Date();
    const currentYear = today.getFullYear();
    const dateA = new Date(a.date);
    dateA.setFullYear(currentYear);
    const dateB = new Date(b.date);
    dateB.setFullYear(currentYear);
    return dateA - dateB;
})
.filter(event => {
    const today = new Date();
    const currentYear = today.getFullYear();
    const eventDate = new Date(event.date);
    eventDate.setFullYear(currentYear);
    return eventDate > today;
})
.splice(0, 5)
.map(event => {
...

How to handle states in typescript?

Hello I am new to typescript and I have job to do here.
I need to make dynamic class, something like in this code bellow.

import React, { ReactNode, useState } from "react";

interface Props {
  text: ReactNode;
}

const ListItem = ({ text }: Props) => {
    let [showMore, setShowMore] = useState(false);

    return (
        <div className="item">
            <div>
                <div className={`text ${showMore ? "active" : ""}`}>{text}</div>
            </div>
            <button onClick={() => setShowMore((s) => !s)}>Show more</button>
        </div>
    );
};

But I need to implement it to this code and I have no idea how to do it, because I don’t understand this syntax from someone who wrote it.
When I try to implement previous code, I have problem with react hooks rendering in this syntax.

I hope you understand my problem

type DeliveryBranchHitProps = {
  hit: SearchIndex.DeliveryBranch;
};
const DeliveryBranchHit = ({
  hit: delivery_branch,
}: DeliveryBranchHitProps): JSX.Element => (
  <>
      <div className={`branch-opening-week ${showMore ? "active" : ""}`}>
        <p>
          <span className="branch-day">Monday:</span>
          {delivery_branch.opening_monday}
        </p>
        <button onClick={() => setShowMore((s) => !s)}>Show more</button>

    </div>
  </>
);

Return dynamically populated object literal in javascript

A little new to JS. It seems to me something like this would be possible, but after spending a few hours of getting nowhere, I’m wondering if there actually is a way to make something like this work. It’s just a function that returns an object, but the key values are set in the function instead of being passed to it:

function makeProduct() {
      return {
          Id = '0',
          Name = document.getElementById('Name').value,
          Price = document.getElementById('Price').value,
          Category = document.getElementById('Category').value
      };
    }

It seems like this would save a lot of duplicate code, instead of having to get the user input, assign it to variables, and then populate the object with the more proper syntax:

function product(id, name, price, category) ...

I was able to accomplish what I was trying to do with a class, but it does generate a lot more code. If you had a large object, you are typing a lot of the same things multiple times.

I do have some code that works using jquery, but if I try and put it in a function that returns the object, it errors out on me, too.

The whole point of the code is to call the function, return the object, and use Axios to send it to my webAPI.

async function makeGetRequest() {

  var product = makeProduct();

let res = await axios.post('http://localhost:56730/api/product/', product);

let data = res.data;
console.log(data);
}

And it does work as expected with my class.

Also, because of the keywords in this question, this is something really hard to search for and get relevant answers.

VSCode multiple versions of custom snippets

I am creating custom javascript snippets in VS Code. I have a snippet that creates a React component class, but using the same prefix, I want to have a slightly different version of the react component class. This is my code:

   "Creates a React component class": {
        "prefix": "rcc",
        "body": [
          "import React from 'react'",
          "",
          "class ${1:className} extends React.Component {",
          "    render() {",
          "        return (",
          "            <div>",
          "",
          "            </div>",
          "        )",
          "    }",
          "}",
          "",
          "export default ${1:className}"
        ],
        "description": "Creates a React component class"
    },

I want to type rcc and have it give me two options, one is default, and the other pastes this code:

   "Creates a React component class": {
        "prefix": "rcc",
        "body": [
          "import React from 'react'",
          "",
          "class ${1:className} extends React.Component {",    
          "    render() {",
          "        const runCallback = (cb) => {",
          "            return cb()",
          "         }",
          "        return (",
          "            <div>",
          "",
          "            </div>",
          "        )",
          "    }",
          "}",
          "",
          "export default ${1:className}"
        ],
        "description": "Creates a React component class"
    },

JS d3 obtained element width is less than the hardcoded value

CSS:

#full_bar {
  width: 240px;
}

JS:

console.log(d3.select('#full_bar').style('width'));

Output is ‘208px’.
If I change the hardcoded value of ‘240’ to a different one, the output is always a fixed percentage of the hardcoded value. I assume the CSS style is being overwritten, but I don’t know where. If I inspect it in the browser it says the width is 240px, and the visual bar doesn’t appear to be cropped at all.
Any advice?

Discord.js Interaction await messages cannot get message objects

Once a user creates an interaction in a discord channel I want to listen for new incomming messages in that channel. Here is the code I got

if(interaction.customId.startsWith("TRIGGER")){
let filter = m => m.author.id === interaction.author.id
interaction.channel.send(`Are you sure to delete all data? `YES` / `NO``).then(() => {
  interaction.channel.awaitMessages(filter, {
      max: 1,
      time: 30000,
      errors: ['time']
    })
    .then(message => {
      message = message.first()
      if (message.content.toUpperCase() == 'YES' || message.content.toUpperCase() == 'Y') {
        message.channel.send(`Deleted`)
      } else if (message.content.toUpperCase() == 'NO' || message.content.toUpperCase() == 'N') {
        message.channel.send(`Terminated`)
      } else {
        message.channel.send(`Terminated: Invalid Response`)
      }
    })
    .catch(collected => {
        interaction.channel.send('Timeout');
    });
})

However I dont get the message objects. Its like no messages are send

How can I solve this issue ?

What is the best way to account for some events in an input feild?

Nested if statements for checking whether the fields are empty or complying with other parameters

   if (Name != '' && age != '') {
    if(age >= 18)
    alert("Successfully Submitted!"); 

    else
    alert("you must be over 18 :(");
    }

    else
    alert("cant be empty :(");

how do i check for individual fields with multiple parameters and respond accordingly for each event without having to nest a million if statements?

Change one charter in state while typing – reacjs

I have a state:

const [numIndexZero, setNumIndexZero] = useState("****");

And I have an input that I type 4 numbers.

How can I change each charter when i typing a number?

Meaning that, if I type “1” then the state will be “1***” .

If I type “12” then the state will be “12**” ,

If I type “123” then the state will be “123*” ,

If I type “1234” then the state will be “1234”.

Any help??

How to connect different MongoDB collections to React

Please help me out with this as I can’t find the answer anywhere.

My MongoDB Database name is myWebsiteDB:

  • myWebsiteDB has 2 collections: dinners and emails.
  • I have connected dinners collection to use in my website as a CRUD app – works fine.
  • Now I want to save data from Email Subscription section’s input field to the emails collection on my website.
  • These 2 collections are for saving 2 different data intentions, so I don’t want to join them.

I tried setting up the emails collection Schema and connecting it to my React App exactly like the way I connected the dinners collection before, here are the challenges that I’m facing:

  1. When I click the Submit Email button, it doesn’t work and the errors returned from the server’s terminal seem like it’s the validation for the dinners collection, not the emails collection that I
    m trying to write in. See screenshot

  2. Am I using validator and writing the new Emails schema right? Do I need to specify the {collection: collection name} like below?

Here are my code:

Emails Model (Emails.js):

const mongoose = require('mongoose')
const validator = require('validator')

const EmailSchema = new mongoose.Schema({
    email: {
        type: String,
        trim: true,
        lowercase: true,
        unique: true,
        validate: {
            validator: validator.isEmail,
            message: 'Please input a valid email address',
            isAsync: false
        }
    }
}, {collection: "emails"})

const Emails = mongoose.model('Emails', EmailSchema)
module.exports = Emails

Dinner Model (Dinner.js):

const mongoose = require('mongoose')

const DinnerSchema = new mongoose.Schema({
    foodName: {
        type: String,
        required: true,
    },
    isVegetarian: {
        type: Boolean,
        required: true,
    },
    priceRange: {
        type: String,
        required: true,
    }
}, {collection: "dinners"})

const Dinner = mongoose.model("Dinner", DinnerSchema)
module.exports = Dinner

Server side index.js:

const express = require("express") // Set up an express server
const mongoose = require("mongoose") // Import Mongoose library
const cors = require('cors') // Import CORS to communicate with frontend
const app = express() // Initializing our express server

const DinnerModel = require('./models/Dinner')
const EmailModel = require('./models/Emails')

app.use(express.json()) // Setting up Middleware
app.use(cors())

// Connect to MongoDB
mongoose.connect(
    'mongodb+srv://myusername:[email protected]/myWebsiteDB?retryWrites=true&w=majority', 
    {
        useNewUrlParser: true,
    }
)

// Create:
app.post("/insert", async (req, res) => {
    const foodName = req.body.foodName
    const isVegetarian = req.body.isVegetarian
    const priceRange = req.body.priceRange
    const email = req.body.email

    // Dinner Ideas App:
    const dinner = new DinnerModel(
        { 
            foodName: foodName, 
            isVegetarian: isVegetarian,
            priceRange: priceRange,
        }
    )

    // Email:
    const emailData = new EmailModel(
        {
            email: email
        }
    )

    try {
        await dinner.save()
        await emailData.save()
        res.send("data inserted")
        
    } catch(err) {
        console.log(err)
    }
})

// Read:
app.get("/read", async (req, res) => {
    DinnerModel.find({}, (err, result) => {
        if (err) {
            res.send(err)
        }
        res.send(result)
    })
})

// Update:
app.put("/update", async (req, res) => {
    const newFoodName = req.body.newFoodName
    const id = req.body.id

    try {
        await DinnerModel.findById(id, (err, updatedFood) => {
            updatedFood.foodName = newFoodName
            updatedFood.save()
            res.send("update")
        }).clone()
    } catch(err) {
        console.log("The error is: " + err)
    }
})


app.delete("/delete/:id", async (req, res) => {
    const id = req.params.id

    await DinnerModel.findByIdAndRemove(id).exec()
    res.send("deleted")
})

// Creating a port:
app.listen(3001, () => {
    console.log("Server is up on: http://localhost:3001")
})

React code with CRUD using the dinners collection:

import React, { useState, useEffect } from "react"
import './DinnerIdeas.css'
import Axios from "axios"
import FoodListComponent from "../FoodListComponent";
import FormComponent from "../FormComponent";


function DinnerIdeas() {

    const [foodName, setFoodName] = useState('')
    const [isVegetarian, setVegetarian] = useState(false)
    const [priceRange, setPriceRange] = useState('$')
    const [newFoodName, setNewFoodName] = useState('')
    const [foodList, setFoodList] = useState([])
  
    // Read:
    useEffect(() => {
      let unmounted = false
      Axios.get("http://localhost:3001/read")
      .then((response) => {
        if (!unmounted) {
          setFoodList(response.data)
        }
      })
      .catch(error => {
        console.log(`Hey, the error is ${error}`)
        return
      })
      return () => {
        unmounted = true
      }
    }, [foodList])
  
    // Create:
    const addToList = () => {
      Axios.post(
        "http://localhost:3001/insert", 
        {
          foodName: foodName,
          isVegetarian: isVegetarian,
          priceRange: priceRange,
        }
      )
    }
  
    // Update:
    const updateFood = (id) => {
      if (newFoodName) {
        Axios.put("http://localhost:3001/update", {
          id: id,
          newFoodName: newFoodName,
        })
        .catch(error => console.log(`Hey, the error is ${error}`))
      }
    }
  
    // Delete:
    const deleteFood = (id) => {
      Axios.delete(`http://localhost:3001/delete/${id}`)
    }
    
    return (
      <section className="dinner-ideas">
        <FormComponent
          setFoodName={setFoodName}
          setVegetarian={setVegetarian}
          setPriceRange={setPriceRange}
          addToList={addToList}
        />
        <FoodListComponent 
          foodList={foodList} 
          setNewFoodName={setNewFoodName}
          updateFood={updateFood} 
          deleteFood={deleteFood}
          newFoodName={newFoodName}
        />
      </section>
    );
  }
  
  export default DinnerIdeas;

React Footer Component that let users put in their emails to subscribe, this will write to the emails collection:

import React, { useState } from "react"
import Axios from "axios"



export default function FooterComponent() {

    const [email, setEmail] = useState('')

    const subscribeEmail = () => {
        Axios.post(
            "http://localhost:3001/insert",
            {
                email: email
            }
        )
    }


    return (
        <footer>
            <div>Created by higherstates &copy; 2021</div>
            <div>
                <h3>Interested in further deals?</h3>
                <input
                    type='email'
                    placeholder="Give us your email"
                    onChange={(event) => {setEmail(event.target.value)}}
                />
                <button 
                    type="submit"
                    onClick={subscribeEmail}
                >
                    Submit Email
                </button>
            </div>
        </footer>
    )
}

Please guide me on how to fix this, thank you! 🙂

Using GSAP and ScrollTrigger to create a number counter (where numbers exist)

I have a section which showcases statistics.

  • Some of these statistics are numbers (i.e. 145);
  • Some are numbers, characters and symbols (i.e. 65K+ or $20.00)
  • Some are just purely text (i.e. “text”)

When this section is in view, I want stats which contain a number to count up (and naturally stats that don’t contain numbers to not count up).

The effect I’m trying to achieve is:

  • All .statsBannerCard‘s are set to visibility: hidden
  • User scrolls to section
  • JS checks if first .statsBannerCard contains number; if yes, counts up (this single card is visibility: visible now).
  • Then once the counter for the first card is complete, make the second card visible and check if it contains a number, and so on.

The proceeding card is essentially shown once the previous card counter is complete. If a card just contains text (so we can’t count up), it will just show the card and move on.

Current issue:

In my demo below, I’m using the data-number attribute to determine what number the card needs to count up to. When scrolling down, the first counter works (because it is a pure integer), however, it stops working when characters, symbols or letters are involved.

Demo:

$(function() {

  gsap.registerPlugin(ScrollTrigger);


  $(".statsBannerCard__statistic").each(function(index, element) {
    var count = $(this),
      zero = {
        val: 0
      },
      num = count.data("number"),
      split = (num + "").split("."), // to cover for instances of decimals
      decimals = split.length > 1 ? split[1].length : 0;

    gsap.to(zero, {
      val: num,
      duration: 2,
      scrollTrigger: element,
      onUpdate: function() {
        count.text(zero.val.toFixed(decimals));
      }
    });
  });

});
.spacer{
  height: 100vh;
  background: lightblue;
}

.statsBanner{
  background: #F283D6;
  padding: 100px 0;
}

.statsBanner__intro{
  margin-bottom: 60px;
}

.statsBannerCard{
  /* visibility: hidden; */
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.0/ScrollTrigger.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">


<section class="spacer">
  Scroll down
</section>


<section class="statsBanner">
  <div class="container">

    <div class="row">
      <div class="col-12">
        <div class="statsBanner__intro text-center">
          <h2>Start counter when this section is in view.</h2>
        </div>
      </div>
    </div>

    <div class="row justify-content-evenly">


      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="145">145</span>
        </div>
      </div>

      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="Text">Text</span>
        </div>
      </div>

      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="$20,000">$20,000</span>
        </div>
      </div>

      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="60K+">60K+</span>
        </div>
      </div>



    </div>
  </div>
</section>

SetInterval can’t be stopped by clearInterval when using useEffect

I’ve tried to implement a function that starts a count down when the isPlaying variable is truthy and it stops when it’s falsy, in general, it doesn’t work and all it does is just start multiple intervals simultaneously,
The isPlaying changes when the video stops or start playing again

 let interval
    useEffect(() => {
            if (isPlaying) {
                interval = setInterval(() => {
                    setTimePassed((time) => time + 1)
                }, 1000);
            } else {
                console.log('clear interval');
                clearInterval(interval);
            }
            return () => clearInterval(interval);
        }, [isPlaying])

React Native error Element type is invalid: expected a string

I am using react-native-sass-transformer package with React Native, and I cannot get past the following error:

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

Check the render method of `App`.

This error is located at:
in RCTView (created by View)
in View (created by ScrollView)
in RCTScrollView (created by ScrollView)
in ScrollView (created by ScrollView)
in ScrollView (created by App)
in App (created by ExpoRoot)
in ExpoRoot
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:149:8 in registerError
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:60:8 in errorImpl
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:34:4 in console.error
at node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:104:6 in reportException
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:172:19 in handleException
at node_modulesreact-nativeLibrariesCoreReactFiberErrorDialog.js:43:2 in showErrorDialog
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:15792:34 in logCapturedError
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:15884:20 in update.callback
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:7199:2 in callCallback
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:7220:20 in commitUpdateQueue
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:16632:25 in commitLifeCycles
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:19216:22 in commitLayoutEffects
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:93:4 in invokeGuardedCallbackProd
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:318:2 in invokeGuardedCallback
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:18952:29 in commitRootImpl
at node_modulesschedulercjsscheduler.development.js:468:23 in unstable_runWithPriority
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:18791:17 in commitRoot
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:18192:12 in performSyncWorkOnRoot
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:5911:33 in runWithPriority$argument_1
at node_modulesschedulercjsscheduler.development.js:468:23 in unstable_runWithPriority
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:5906:23 in flushSyncCallbackQueueImpl
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:5893:28 in flushSyncCallbackQueue
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:17745:30 in scheduleUpdateOnFiber
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:21484:23 in updateContainer
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:22144:17 in render
at node_modulesreact-nativeLibrariesReactNativerenderApplication.js:58:4 in renderApplication        
at node_modulesreact-nativeLibrariesReactNativeAppRegistry.js:117:25 in runnables.appKey.run
at node_modulesreact-nativeLibrariesReactNativeAppRegistry.js:202:4 in runApplication
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:414:4 in __callFunction
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:113:6 in __guard$argument_0
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:365:10 in __guard
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:112:4 in callFunctionReturnFlushedQueue

I have added the code inside metro.config.js and app.json as specified here.

My code inside App.js:

import { ScrollView, StyleSheet } from 'react-native';

import LoginPage from './src/Components/Pages/LoginPage/LoginPage';

export default function App() {
    return (
        <ScrollView style={styles.container}>
            <LoginPage />
        </ScrollView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    }
});

LoginPage.jsx:

import { View } from 'react-native';
const LoginPage = () => {
    return (
        <View></View>
    );
};

export default LoginPage;

Even if I revert the changes made for react-native-sass-transformer, the error persists. I do not have any idea of what to try.