Logging out after posting

im getting error, that my logging status is refreshed after posting and when i tried to repair it i just got more errors and i dont know how to straighten everything. Here i publish my code, if u can help me or get me any advise i will be very thankful. Thanks.

I guess that its all in the “isAuth” and “setIsAuth” but idk, and it looks to me, like the only one of them is needed, but im trying to learn from tutorial where both were used

App.js

import React, { Component } from 'react';
import './css/main.css';
import { BrowserRouter as Router, Routes, Route, Link, Navigate } from 'react-router-dom';
import Home from './pages/Home';
import CreatePost from './pages/CreatePost';
import Calendar from './pages/Calendar';
import Login from './pages/Login';
import { signOut } from 'firebase/auth'
import { auth } from './firebaseconf';


class App extends Component {


  constructor(props) {
    super(props);
    this.state = {
      setIsAuth: false,
      isAuth: false
    };
  }


  signIn = () => {
    this.setState({ setIsAuth: true });
  }

  signUserOut = () => {
    signOut(auth).then(() => {
      localStorage.clear();
      this.setState({ setIsAuth: false });
      window.location.pathname = "/login";
    });
  }

  render() {
    return (
      <Router>
        <nav>
          <Link to="/">Home</Link>
          {!this.state.isAuth ? (
            <Link to="/login">Login</Link>
          ) : (
            <>
              <Link to="/createpost"> Create New Post</Link>
              <Link to="/calendar"> Calendar</Link>
              <button onClick={this.signUserOut}>Log out</button>
            </>
          )}
        </nav>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/login" element={<Login setIsAuth={this.signIn} />} />
          <Route path="/createpost" element={<CreatePost setIsAuth={this.signIn} />} />
          <Route path="/calendar" element={<Calendar />} />
        </Routes>
      </Router>


    );
  }
}

export default App;

CreatePost.js

import React, { Component } from 'react';
import { addDoc, collection } from 'firebase/firestore';
import { db } from '../firebaseconf';

class CreatePost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            setTitle: "",
            setPostText: "",
        };
    }

    sTitle = (event) => {
        this.setState({ setTitle: (event.target.value) });
    }

    sPostText = (event) => {
        this.setState({ setPostText: (event.target.value) });
    }

    collectionRef = collection(db, "posts");

    createPost = async () => {
        await addDoc(this.collectionRef, { title: this.state.setTitle || null, postText: this.state.setPostText || null });
        window.location.pathname = "/";
    }


    render() {
        return (
            <div className="cpPage">
                <div className="cpContainer">
                    <h1>Create a Post</h1>
                    <div className="inputGp">
                        <label>Title:</label>
                        <input
                            placeholder="Title..."
                            onChange={this.sTitle}
                        />
                    </div>
                    <div className="inputGp">
                        <label>Post:</label>
                        <textarea
                            placeholder="Write your post..."
                            onChange={this.sPostText}
                        />
                    </div>
                    <button onClick={this.createPost}>Add your post</button>
                </div>
            </div>
        );
    }
}
export default CreatePost;

Login.js

import React from 'react';
import { auth, provider } from '../firebaseconf';
import { signInWithPopup } from 'firebase/auth';
import { useNavigate } from 'react-router-dom';

function Login(setIsAuth) {
    let navigate = useNavigate();

    const singInWithGoogle = () => {
        signInWithPopup(auth, provider).then((result) => {
            localStorage.setItem("isAuth", true);
            setIsAuth();
            navigate("/");
        });
    };

    return (
        <div>
            <button onClick={singInWithGoogle}>Sign in with Google</button>
        </div>
    );

}
export default Login;

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;
    }
 });

});

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

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?

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: [],
          },
        ],
      },
    ],
  }, ],

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?

How to throw an error from API and catch it from client side?

I have two different projects. First one is the outer shell of the site, basically html+js. There is a registration function where you send data in the POST array:

const registerUser = async function(e) {
 e.preventDefault();

 let email = document.querySelector('#email').value;
 let password = document.querySelector('#password').value;
 let confirmPassword = document.querySelector('#confirm_password').value;

 const formData = new FormData();
 formData.append('email', email);
 formData.append('password', password);
 formData.append('confirm_password', confirmPassword);

 try {
   await fetch(`${API}/users`, {
   method: 'POST',
   body: formData,
   }).then((response) => {
     email = '';
     password = '';
     confirmPassword = '';
     console.log(response);
   })
 }
 catch(err) {
   console.log(err);
 }
}

The second one is a simple REST API on PHP where client side sends data to. It receives the POST array and registers the user.

function registerUser($db, $postData) {
 $email = mysqli_real_escape_string($db, $postData["email"]);
 $password = mysqli_real_escape_string($db, $postData["password"]);
 $confirm_password = mysqli_real_escape_string($db, $postData["confirm_password"]);

 if(empty($postData) || !isset($email) || empty($email) || !isset($password) || empty($password) 
 || !isset($confirm_password) || empty($confirm_password)) return false;

 if($password !== $confirm_password) {
   $_SESSION["error"] = "Passwords don't match!";
   return false;
 }

 $user = mysqliQuery($db, "SELECT * FROM `users` WHERE `email` = '$email';");

 if(mysqli_num_rows($user) > 0) {
   $_SESSION["error"] = 'User with such email already exists!';
   return false;
 };

 $date = date("Y-m-d H:i:s");
 $hashPass = password_hash($password, PASSWORD_DEFAULT);
 $nameFromEmail = strstr($email, '@', true); 

 if(mysqliQuery($db, "INSERT INTO `users` (`id`, `email`, `password`, `registered_at`, `name`) 
 VALUES (NULL, '$email', '$hashPass', '$date', '$nameFromEmail');")) {
   http_response_code(201);
 }

 else {
   http_response_code(401);
 }
}

But the problem is, I don’t know how to throw an error if received email already exists in the database. Is there any way to send an error from PHP server side in response to client side after fetching?