React typescript onClick event typing

I’m making a React + typescript project. And i have number button which looks like this:

<button className="num" type='button' value={'1'} onClick={inputHandler}>1</button>

You can notice that i also have onClick={inputHandler} on that button:

  const inputHandler = (event: any) => {
   event.preventDefault();
   setInput(prev => prev.replace('_', event.target.value));}

This handler taking a value prop of button and setting it in to the input. So i am stucked on typing event for this handler. Every type i am defining returns:

Property ‘value’ does not exist on type ‘EventTarget’.

If i typing it as “any”, obviously it working. But i need to define exact type for it. Help me please.

Animation not working properly on another website – HTML/CSS/JS

I have the following code:

var basicTimeline = anime.timeline({
  autoplay: false,
});

var pathEls = $(".check");
for (var i = 0; i < pathEls.length; i++) {
  var pathEl = pathEls[i];
  var offset = anime.setDashoffset(pathEl);
  pathEl.setAttribute("stroke-dashoffset", offset);
}

basicTimeline
  .add({
    targets: ".text",
    duration: 1,
    opacity: "0"
  })
  .add({
    targets: ".button",
    duration: 1300,
    height: 20,
    width: 81,
    backgroundColor: "#717F7E",
    border: "0",
    zIndex: 0,
    borderRadius: 100
  })
  .add({
    targets: ".progress-bar",
    duration: 2000,
    width: 81,
    easing: "linear"
  })
  .add({
    targets: ".button",
    width: 0,
    duration: 1
  })
  .add({
    targets: ".progress-bar",
    width: 40,
    height: 39,
    delay: 500,
    duration: 750,
    borderRadius: 80,
    backgroundColor: "#71DFBE",
    left: 20
  })
  .add({
    targets: pathEl,
    strokeDashoffset: [offset, 0],
    duration: 200,
    easing: "easeInOutSine"
  });


$(".button").click(function(e) {
  e.preventDefault();
  let validationOK = true;

  const form = document.forms.myform;
  let data = Object.fromEntries(new FormData(form).entries())
  for (let entrie in data) {
    if (!form[entrie].checkValidity()) {
      validationOK = false
      form[entrie].classList.add('shakingErr')
      setTimeout(() => {
        form[entrie].classList.remove('shakingErr')
      }, 820)
    }
  }

  if (validationOK) {
    basicTimeline.play();

    // submit action
    fetch(form.action, {
        method: form.method,
        body: JSON.stringify(data),
        headers: {
          Accept: 'application/json'
        }
      })
      .finally(() => {
        window.location = "thankyou.html"
      })
  }
});
/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type="text"]:focus,
input[type="email"]:focus,
#subject:focus {
  background: var(--bgFormElsFocus);
  transform: scale(1.02);
  transition: transform 0.2s ease-in-out;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

form .shakingErr {
  border-color: red;
  animation: shake 0.82s forwards;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}


/* fancy button styles */

.buttonWrapper {
  height: 39px;
  width: 81px;
  position: relative;
}

.button {
  background: #2B2D2F;
  height: 39px;
  width: 81px;
  text-align: center;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
  cursor: pointer;
  border-radius: 4px;
  z-index: 10;
}

.text {
  font: .8rem/1 poppins;
  color: #71DFBE;
  position: absolute;
  top: 50%;
  transform: translateY(-52%);
  left: 0;
  right: 0;
  cursor: pointer;
}

.progress-bar {
  position: absolute;
  height: 20px;
  width: 0;
  left: 40px;
  top: 50%;
  border-radius: 200px;
  transform: translateY(-50%) translateX(-50%);
  background: black;
}

svg {
  width: 15px;
  position: absolute;
  top: 50%;
  left: 20px;
  transform: translateY(-50%) translateX(-8px);
}

.check {
  fill: none;
  stroke: #FFFFFF;
  stroke-width: 3;
  stroke-linecap: round;
  stroke-linejoin: round;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.js">
  </script>

</head>

<body>
  <!-- start contact section -->
  <section id="contact">
    <div class="container" data-aos="fade-up">
      <div class="contactform">
        <div style="text-align:center">
          <div class="section-title">
            <h2><br />Get In Touch</h2>
          </div>
          <p>Feel Free To Reach Out To Me Through This Form! </p>
        </div>
        <div class="row">
          <div class="column">
            <form name="myform" action="https://formspree.io/f/xrg123232jbqpq" id="my-form" method="POST" novalidate>
              <label for="firstname">First Name</label>
              <input type="text" id="first name" name="firstname" required placeholder="Your First Name.." required>
              <label for="lastname">Last Name</label>
              <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
              <label for="email">Email:</label>
              <input type="email" id="email" name="email" placeholder="Your Email.." required>
              <label for="subject">Subject</label>
              <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
              <!-- <input type="submit" value="Submit"> -->
              <div class='buttonWrapper'>
                <button class="button" type="submit">
                  <div class="text">Submit</div>
                </button>
                <div class="progress-bar"></div>
                <svg x="0px" y="0px" viewBox="0 0 25 30" style="enable-background:new 0 0 25 30;">
                  <path class="check" class="st0" d="M2,19.2C5.9,23.6,9.4,28,9.4,28L23,2" />
                </svg>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </section>
  <script src="script.js"></script>
</body>

</html>

When you run the above code, enter the information in the fields, and click submit, then the animation seems to be working fine. However, on my end, when I put this code into my website, then this is the result on my end: https://watch.screencastify.com/v/GNnmF7yyNKjC5FIiEw4m

As you can see, the animation plays very weirdly on my end, and it does not even play it properly. Is there some error in the code above because it seems to be working fine here, but when I put this into my website, it causes that weird animation and does not properly play. Thanks.

Why’s my form action still being triggered when validating the form despite using e.preventDefault()?

I’d like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted – in other words, the form’s action won’t be triggered.

I’ve tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.

I’ve hit a wall with this and can’t figure out what I’m doing wrong. How can rectify this?

html:

<form method="POST" id="form" action="/post.php">
  <span class="nameError"></span>
  <input type="text" class="name" name="name" placeholder="Name" required/>
            
  <input class="button" type="submit" value="Submit"/>
</form>

Here’s my jquery:

let name = $('.name');
let nameError= $('.nameError');

$(document).ready(function() {

$('input[type=submit]').on('click', function(e) {
    if (name.length > 20) {
        e.preventDefault();
        fullNameError.val("Too many characters!");
        return false;
    }
 });

});

Why does one use the const keyword for functions? [closed]

Keywords convey meaning. In most programming languages, the keyword for denoting a constant is usually used just for that. So consider the following two almost-equivalent statements in JavaScript:

  • const foo = (a, b) => return a + b
  • function foo(a, b) { return a + b }

Why on Earth would one choose the former? Is it just popularity? I find the latter so much easier to read. E.g. when looking through code, by using the function keyword, I immediately realize that it is a function. When using const however, my eyes must also scan for a lambda, because people use the const keyword for pretty much everything these days.

Or is there some convincing argument to use const?

How to pass a class type as parameter?

As described here: Declare class type with TypeScript (pass class as parameter) i can pass a class type as parameter.

There is a problem.

export namespace customCommand {
    export class Command {
        public constructor(parameter?: any) {

        }
    }

    export function register(command: typeof Command) {

    }
}

When i do this

customCommand.register(Map)

or

customCommand.register(Object)

There is no errors. I know that typeof Command and typeof Map both return the same result.

But how can i protect this and pass only Command type?

FirebaseError: Expected type ‘Pc’, but it was: a function

I’m trying to add a document inside a subcollection inside an already existing document. When the function runs, I keep getting this error saying: FirebaseError: Expected type ‘Pc’, but it was: a function.

Code:

const docRef = doc(db, "user", data.id);
const colRef = collection(docRef, 'teams')
addDoc(colRef, {
   id: response.data.account.id,
   role: 'owner',
   uid: data.id,
});

image doesn’t render when using next.js Image tag

I have an image located in the public/img directory. I want to render it using the next.js built-in <Image/> tag.

here is the code I have written:

     <Image
                onClick={hideModal}
                alt="close_button"
                src="/img/close_button.png"
                width="20px"
                height="20px"
              />

but nothing is shown on the page (not even the alt-text).

the thing is when I use the <img/> tag, it works as expected but with the <Image/>, it doesn’t

Construct MongoDB query from GraphQL request

Let’s say we query the server with this request, we only want to get the following user’s Email, My current implementation requests the whole User object from the MongoDB, which I can imagine is extremely inefficient.

GQL
{
  user(id:"34567345637456") {
    email
  }
}

How would you go about creating a MongoDB filter that would only return those Specified Fields? E.g,

JS object
{
   "email": 1
}

My current server is running Node.js, Fastify and Mercurius

Javascript + Rest + Google Chart: g is undefined

I am coding a website getting data from an home made API and publishing that on a google chart.

on my chart area, I get a text or a red background “g is undefined”.

It is driving me crazy, any clue of what I am doing wrong?

google.charts.setOnLoadCallback(drawChart);
var chart

function drawChart() {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Date');
    data.addColumn('number', 'Positive');
    data.addColumn('number', 'Negative');
    data.addColumn('number', 'Mixed');
    data.addColumn('number', 'Neutral');

    var request = new XMLHttpRequest()

    // Open a new connection, using the GET request on the URL endpoint
    request.open("POST", apiEndPoint + "/dailystats", true);
    request.setRequestHeader('Content-Type', 'application/json');
    request.send(JSON.stringify({"media":media,"period":parseInt(period)}));


    request.onload = function() {
    var restcall = JSON.parse(this.response)
        if (request.status >= 200 && request.status < 400) {
            restcall.forEach(metric => {
                data.addRows([[metric.date,metric.sentiments.positive,metric.sentiments.mixed,metric.sentiments.neutral,metric.sentiments.negative]])
            })
        }
    }
    var options = {
    chart: {
        title: 'Box Office Earnings in First Two Weeks of Opening',
        subtitle: 'in millions of dollars (USD)'
    },
    width: 900,
    height: 500
    };

    chart = new google.charts.Line(document.getElementById('linechart_frame'));

    chart.draw(data, google.charts.Line.convertOptions(options));
}```

Thanks!

Creating a Filters organism in Storybook [with React]

I’ve been trying to resolve this task for the last few days, but holy moly I’ve been running in circles with every solution I could think of. Right now I feel drained and I’m in serious need of help.

To give a bit of background, we use Storybook at work. I’m supposed to create this Filter organism, which could have the following structure that was suggested by another developer.

<FilterBar onRemove onAdd onChange>
  <FilterBarItem optional={ false } onChange>
    <Dropdown />
  </FilterBarItem>
  <FilterBarItem optional={ true } onChange>
    <TextField />
  </FilterBarItem>
  <FilterBarItem optional={ true } onChange>
    <TextField />
  </FilterBarItem>
  <FilterBarSelect onChange>
    <Dropdown />
  </FilterBarSelect>
</FilterBar>

First of all, let me try to explain how this should work, at least from my understanding (still not 100% clear on what we’re trying to achieve, but I guess we can take any other e-commerce filter out there as example).

So the user can add or remove filters to narrow down a list of products to their preference. Each filter also have a few options to choose from. For example:
Let’s say I’m looking for white shoes size 41 on a website. I’m going to apply the size filter (which should have some options), I’m going to apply a color filter maybe, and some type of footwear I want (shoes).

Coming back to our structure.

FilterBar I suppose it’s going to be the main wrapper and the one that controls if we add or remove filters.

FilterBarItem is going to be the filter itself and now, here’s the first challenge. It doesn’t know which type of child component it’s gonna have, it can be a dropdown of options, it can be a color picker, it can be a normal input field where user can input something, etc.

FilterBarSelection is going to be a styled dropdown, based on the react-select library and it’s going to have some filters options passed in and based on what it’s selected, it will generate a new FilterBarItem.

Ok here’s how I thought about implementing this and what are the issues.

The FilterBar

const FilterBar = ({ children, ...props }) => {
 // Maybe here we can add the array of options we want to pass into FilterBarSelection?
 // Also maybe here too we want to create the onAdd, onRemove functions and pass them into whatever component needs it? For example, onRemove should be passed into the FilterBarItem and the onAdd should be passed into FilterBarSelection since it's the one that controls how many filters we apply?
 // Also if we have a list of filters that can't be removed by the user, I'm guessing they also have to be added here?
 return (
  <div className="someClass">
   <div className="mandatory-filters">
    { children }
   </div>
   <div className="optional-filters">
  { React.Children.map(children, child => (
      React.cloneElement(child, { onAdd={ }, onRemove={ }, ...props }))) }
   </div>
  </div>
 )
}

The FilterBarItem

const FilterBarItem = ({ optional, children }) => {
 // If the filter is optional, then we want to have the ability to remove the filter if the user decides to.
 if(optional) {
   return (
    <>
    { children } // can we determine the type of filter we want to add? For example, like I said before, it can be a simple input
    <button onClick={ onRemove }>Remove</button>
    </>
   )
 }

 return (
  <>
   { children }
  </>
 )
}

The FilterBarSelection

const FilterBarSelection = () => {
 return (
  <ReactSelect 
    isMulti 
    options={ filterOptions } />
 )
}

As you can see, there are a lot of problems I don’t know how to fix. And this is why I needed some help with the implementation because honestly I’ve ran out of ideas.

How can I convert a plain array into an array with objects?

in my vuejs project I’m working on, the information from the api comes in the form of a flat array. I need to edit this incoming data and convert it to the following format.
For example, I need to arrange the parent id of an object to be the id of its parent item.

How can I solve this problem, I am waiting for your ideas.

data from api

{
  "id": 1,
  "parentId": 0,
}, {
  "id": 2,
  "parentId": 0,
}, {
  "id": 3,
  "parentId": 0,
}, {
  "id": 4,
  "parentId": 3,
}, {
  "id": 5,
  "parentId": 3,
}, {
  "id": 6,
  "parentId": 4,
}, {
  "id": 7,
  "parentId": 4,
}, {
  "id": 8,
  "parentId": 5,
}, {
  "id": 9,
  "parentId": 5,
}, {
  "id": 10,
  "parentId": 0,
}

this is how i want to edit data

items: [{
    id: 1,
    parentId: 0,
    children: [{
      id: 10,
      parentId: 1,
    }, ],
    id: 2,
    parentId: 0,
    children: [],
    id: 3,
    parentId: 0,
    children: [{
        id: 4,
        parentId: 3,
        children: [{
            id: 6,
            parentId: 4,
            children: [],
          },
          {
            id: 7,
            parentId: 4,
            children: [],
          },
          {
            id: 8,
            parentId: 4,
            children: [],
          },
        ],
      },
      {
        id: 5,
        parentId: 3,
        children: [{
            id: 9,
            parentId: 5,
            children: [],
          },
          {
            id: 10,
            parentId: 5,
            children: [],
          },
          {
            id: 11,
            parentId: 5,
            children: [],
          },
        ],
      },
    ],
  }, ],

Authentication and authorization using Cookies with React+Redux and ExpressJS

so I am writing an app and for a couple of days I struggle to proplerly authenticate and authorize user.
My express config:

const cookieLifetime = 1000 * 200;
app.use(
  cors({
    origin: "http://localhost:3000",
    methods: ["GET,PUT,POST,DELETE,PATCH,OPTIONS"],
    credentials: true,
    allowedHeaders: `Content-Type, Authorization, X-Requested-With`,
  })
);

app.use(
  session({
    name: `cookie`,
    resave: false,
    saveUninitialized: false,
    store: store,
    secret: `secretttttttt`,
    cookie: {
      secure: false,
      maxAge: cookieLifetime,
      httpOnly: false,
      sameSite: false,
    },
  })
);

Login route

router.post(`/login`, async (req, res) => {
  try {
    const user = await User.findByCredentials(req.body.email, req.body.password);
    if (!user) {
      req.session.error = `Niepoprawny adres email lub hasło`;
      res.status(404).send(req.session.error);
    }
    req.session.user = user;
    res.status(200).send(req.session);
  } catch (e) {
    res.status(404).send();
  }
});

As far everything is working correctly. I would like to add a couple of protected routes, so I am using auth middleware in route, which looks

const isAuth = (req, res, next) => {
  console.log(req.cookies);
  if (req.cookies.cookie) {   
    next();
  } else {
    req.session.error = "Musisz być zalogowany, aby wykonać tą operacje";
    res.status(400).send(req);
  }
};

module.exports = isAuth;

In my front I would like to login user and then check if user is logged in to access routes, I think my idea of routing is decent but here is how it looks

const Login = () => {
  const dispatch = useDispatch();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(null);
  const navigate = useNavigate();

  const user = useSelector((state) => state);

  const fetchData = () => {
    dispatch(loginUser({ email, password }));
    setLoading(true);
  };

  const handleFormSubmit = (e) => {
    e.preventDefault();
    fetchData();
  };

  useEffect(() => {
    if (user.user !== null && loading === true) {
      setLoading(false);
      if(user.user.userRole === "reviewer"){
        navigate("/reviewerView", { replace: true });
      } else {
        navigate("/appView", { replace: true });
      }
    }
  }, [user]);

Now finally my final route, which I would like to check if user is logged in based on cookies.

export const PostList = () => {
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState(null);
  const [selectedTopic, setSelectedTopic] = useState("");
  const posts = useSelector((state) => state.post);
  const cookie = Cookies.get("cookie");

  useEffect(() => {
    if ( cookie !== undefined && (posts.length === 0 || posts === undefined)) {
      setIsLoading(true);
      dispatch(getPosts());
    }
    if (posts.posts !== undefined) {
      setIsLoading(false);
    }
  }, [posts, cookie]);

My question is – is my approach correct ? If not what and how can I change it to make it work and look properly ?

JavaScript Edit Website (Specific button doesn’t work like i want to)

I created a script for Tampermonkey to edit every Website, now I want to have, that this button right above the caps lock: –>| (on Mac) switches between buttons when I click on it. Currently it puts some spaces between the words, but that’s what i don’t want. Here’s my script:

     // ==UserScript==
// @name         Edit any Website
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match      *://*/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==
(function () {
    'use strict';
    // javascript:document.body.contentEditable = 'true' ;
    document.designMode = 'on';

    document.querySelectorAll('a').forEach((a) => {
        a.addEventListener('click', (e) => {
            location = e.currentTarget.href;
        })
    })
    })();

Can someone help me?