Why Safari does not store cookie, though Chrome saves it?

There is a Next.js website, it communitace via backend with the help of a proxy.

Frontend runs on port 3000, so Request URL is http://localhost:3000/api/registerFacebookUser

It is then rewritten to the appropriate BE url by proxy.

Response has the Set-Cookie

Set-Cookie: sessionIdTikex=OUhtInL1Esnvr5TSIyJ+sOSg3JiXK1eowKorebGEWMY=; Path=/; Secure; HttpOnly; SameSite=Lax

but only Chrome will show and write cookies into browser, not Safari, why?

Safari Prevent cross-site tracking is NOT turned on.

React authentication isn’t updating properly

when i have my functions in UserAuthContext.js my App isn’t working properly. I try to login but the user is not directet to /browse as it should. But if i put the same code in app.js i can create and login with an account. I don’t know what the reason is
here is the code
https://codesandbox.io/s/cool-euler-eicfr?file=/src/App.js
-not working version (above code belongs to this): https://not-working.netlify.app/
-working version where i have the code in app.js
https://netflix-clone-kasamtde.netlify.app/

How do I render a pug template on success and failure of authentication(passport.js) with variables from the pug template? (express, passport.js, pug)

I am working on the login system using passport.js and express with pug templates. I am trying to render the login page with a message on failure, and if on success I want to redirect the user back to the last page they have been to, of which URL is passed as hidden input inside the pug template. I want to then take that value of that hidden input and put it inside the successRedirect, however it says req is not defined:

router.post("/login",
 body('backurl').trim().escape(),

 passport.authenticate("local", {
  successRedirect: (req.body.backurl),
  failWithError:true
}), function(err,req,res,next){
  return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
}

from my understanding, that happens because of it not having a req since there is no function with req,res,next, so I tried to wrap it with a function that has it:
router.post(“/login”,
body(‘backurl’).trim().escape(),

function(req,res,next){
  passport.authenticate("local", {
    successRedirect: (req.body.backurl),
    failWithError:true
  }), function(err,req,res,next){
    return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
  }
}

);

but it just keeps reloading and doesn’t work and doesn’t go to any URL.

can anybody help me fix this and move the user to the URL from the hidden input while rendering a pug template on failure with variables?

Thanks!

populate product Id inside objects inside array in mongodb

I got an order document structure like that and i want to populate only product and also add the related options and quantity beside the product object

{
_id:ObjectId('61c45d25bdf9c1389879db9f'),
orderItems: [
    {
        options:[
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
        ],
        quantity:4,
        product:ObjectId('61c5e1e7c2ec39450cdf41b7')
    },
    {
        options:[
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
        ],
        quantity:3,
        product:ObjectId('61c5e1e7c2ec39450cdf41b7')
    }
]}

this is the structure i’d like to achieve

{
_id:ObjectId('61c45d25bdf9c1389879db9f'),
orderItems: [
    {
        options:[
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
        ],
        quantity:2,
        product:{
            name:'lorem ipsum dolor set',
            image:'1452877_product.png',
            type:'immo file',
            price:20
        }
    },
    {
        options:[
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
            {_id:ObjectId('61fd914d4a236b94f816c27d'),question:'lorem ipsum dolor set amet', answer:'lorem'},
        ],
        quantity:3,
        product:{
            name:'lorem ipsum dolor set',
            image:'1452877_product.png',
            type:'immo file',
            price:20
        }
    }
]

}

so i write this query to achieve this

const orders = await Order.aggregate([
        {
            $lookup: {
                from:'products',
                let:{
                    productId:'$orderItems.product',
                    options:"$orderItems.options",
                    quantity:"$orderItems.quantity",
                },
                pipeline:[
                    {
                        $match: {
                            $expr: {$in: ["$_id", "$$productId"]}
                        }
                    },
                    {
                        $project:{
                            name:1,
                            price:1,
                            image:1,
                            type:1,
                            options:"$$options",
                            quantity:"$$quantity"
                        }
                    },
                ],
                as:'orderItems.product'
            }
        },
        {
            $unwind:'$user'
        }
    ])

instead i got this weird output that options and quantity located inside the producta and not only that, the product object has the options and two quantity of the initial object before populating

"orderItems": {
            "product": [
                {
                    "_id": "61cfac01b7e712e06a83d89f",
                    "name": "Product number 3",
                    "price": 142,
                    "type": "immo off files",
                    "image": "image-1639832015424-.png",
                    "options": [
                        [
                            {
                                "question": "lorem ipsum dolar set amet 1",
                                "option": "show",
                                "_id": "61c45cdfbdf9c1389879db6b"
                            },
                            {
                                "question": "lorem ipsum dolar set amet 2",
                                "option": "habibi",
                                "_id": "61c45cdfbdf9c1389879db6c"
                            },
                            {
                                "question": "lorem ipsum dolar set amet 3",
                                "option": "wongati",
                                "_id": "61c45cdfbdf9c1389879db6d"
                            },
                            {
                                "question": "lorem ipsum dolar set amet 4",
                                "option": "gortan",
                                "_id": "61c45cdfbdf9c1389879db6e"
                            }
                        ],
                        [
                            {
                                "question": "lorem ipsum dolar set amet 1",
                                "option": "show",
                                "_id": "61c45cefbdf9c1389879db93"
                            },
                            {
                                "question": "lorem ipsum dolar set amet 2",
                                "option": "habibi",
                                "_id": "61c45cefbdf9c1389879db94"
                            },
                            {
                                "question": "lorem ipsum dolar set amet 3",
                                "option": "wongati",
                                "_id": "61c45cefbdf9c1389879db95"
                            },
                            {
                                "question": "lorem ipsum dolar set amet 4",
                                "option": "gortan",
                                "_id": "61c45cefbdf9c1389879db96"
                            }
                        ]
                    ],
                    "quantity": [
                        2,
                        3
                    ]
                },

so please you can tell me what’s wrong about my query and why this weird output happened

add count (.length) each items in option on v-select

I want add count course.length from api each item option on v-select and show data to active based filter
For example, items in v-select: all(count), passed(count) : filter from online.passed, not complete(count) filter from online.complete, etc.

template in vue.js

<template>
  <v-select
    v-model="filter"
    :items="items"
  ></v-select>
  <v-card v-for="online in onlineCourse" :key="online.id">
    <v-card-title>{{online.title}</v-card-title>
    <p v-if="online.complete === 100">{{online.complete}}%</p>
    <p v-else-if="online.complete < 100 && online.complete > 0">{{online.complete}}%</p>
    <p v-else>{{online.complete}}%</p>
  </v-card>
</template>
<script>
  data () {
   return {
     onlineCourse: [],
     filter: 'All',
     items: [
      'All',
      'passed',
      'not complete',
     ],
   }
 }
 method: {
   async getDataOnline () {
    try {
      const request = await Axios.get('v1/courses')
      this.onlineCourse = request.courses
    } catch (error) {
      console.log(error.message);
    }
   }
 }
</script>

.json

 "courses": [
    {
        "id": 1,
        "title": "title1",
        "passed": false,
        "completed": 0
    },
    {
        "id": 2,
        "title": "title2",
        "passed": true,
        "completed": 100
    },
    {
        "id": 3,
        "title": "title3",
        "passed": false,
        "completed": 50
    }
],

pass props with Lazy loading in react-router-dom v6

I need to pass props to the lazy components.

const A = React.lazy(() => import("./A"));

function App() {
return (
      <Suspense fallback={<GlobalLoader />}>
        <Routes>
          <Route path="firstPath" element={<A />} />
        </Routes>
      </Suspense>
)
}

Need to pass props based on path in Lazy Component A. How can I do that?

Overwritting function identifiers while registering identifiers (difference between var and let?)

I’m currently reading the book Secrets of the Javascript Ninja and I do not understand the following behaviour based on an example from chapter 5 explaining how function identifiers are overwritten:

code example from the book:

console.log(typeof fun);

var fun = 3;

console.log(typeof fun);

function fun() {}

console.log(typeof fun);

Output as expected: function / number / number

console.log(typeof fun);

let fun = 3;

console.log(typeof fun);

function fun() {}

console.log(typeof fun);

But when I change the definition to let I get the error that fun has already been decleared. When the lexical environment is created why can I override var but let already blocks the definition of the function declaration?

The attached question, was also answered with “let variables are not initialized until their definition is evaluated.”
What’s the difference between using “let” and “var”?

Is there a RegEx to extract from a string containing a list of delimited by semicolon(;)

I would like to group the key and it’s value (if it has value). The RegEx I found on this website (I lost the post) is almost complete because it separates the key and it’s value.

Example:
my.parameter 10; the.foo "Procedural Map"; pve; server.description "This; is "my", my description,.n"

Current result with [^; "]+|"(?:\"|[^"])*"/g

[
  'server.seed',
  '10',
  'pve',
  'server.level',
  '"Procedural Map"',
  'server.description',
  '"This; is \"my\", server; description,."'
]

Desired result

[
  'my.parameter 10',
  'the.foo "Procedural Map"',
  'pve',
  'server.description "This; is "my", server; description,.n"'
]

Can you help me to improve the RegEx to group the parameter and it’s value?

How to get the number after particular string from array of strings using javascript?

below is an array of strings.

const arr = [
    "list/1/item/1/",
    "item/2/",
    "item/3/subitem/2/",
    "item/4/subitem/3/someother/5",
]

now i have to filter strings that has string starting with item/1/ and is not followed by any other string or is ending with string item/1/

so the expected filtered array is like below,

const filtered_array = [
    "list/1/item/1/",
    "item/2/",
]

from this filtered array i want to get only the number after item/ so the expected output is

const ids = ["1","2"]

i have tried below

var output = arr.filter(x => x.match(/^item/d+|bitem/d+/$/))
            .map(x => x.match(/(?<=^item/)d+|(?<=bitem/)d+(?=/$)/)[0]); //error 
            //here

this gives output like below

const output = ["1", "2", "3", "4"]

because this matches also strings “item/3/subitem/2/”,
“item/4/subitem/3/someother/5”,

how can i fix this regex to match only strings starting with item/3/ and not followed by any other string or is ending with item/3/

also i get object is possibly null on map match line. could someone help me fix this. thanks.

Updating context across components-react.js

I am learning to use useContext with react.js but I now struggle with making it work properly. I am basically trying to create something like a shopping cart, with the cart items being stored in the context. The problem comes when I try to remove an object from the cart because the change doesnt render even tho console.log registers the change…the modal.js apparently just doesnt update.

Modal.js

import React, { useContext } from "react";
import showModal from "../store/meat-context";
import MeatContext from "../store/meat-context";
import CartItem from "./CartItem";
import styles from "./Modal.module.css";

function Modal() {
  const modal = useContext(showModal);
  const { meatState, dispatchMeatState } = useContext(MeatContext);
  if (!modal.showModal) {
    return null;
  }
  console.log(meatState)
  return (
    <div className={styles.backdrop}>
      <div className={styles.modal}>
        
        {meatState.map((meat) => {
          return (
            <CartItem
              name={meat.name}
              price={meat.price}
              id={meat.id}
              key={Math.random()}
              description={meat.description}
            />
            
          );
        })}
      </div>
    </div>
  );
}

export default Modal;

when the modal renders for the first time, it correctly displays and consolelogs the expected content of the cart which looks like this for example:

[
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    },
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    },
    {
        "name": "Schnitzel",
        "description": "A german specialty!",
        "price": 16.5,
        "id": "m2"
    },
    {
        "name": "Barbecue Burger",
        "description": "American, raw, meaty",
        "price": 12.99,
        "id": "m3"
    },
    {
        "name": "Green Bowl",
        "description": "Healthy...and green...",
        "price": 18.99,
        "id": "m4"
    }
]

now when I try to add an item by clicking add, it renders without any problem. But when I try to remove an item, the console.log prints the correct updated state but the cart doesnt render any change. Here is the context for reference:

meat-context.js

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

const MeatContext = React.createContext({ meatState: [] });

export function MeatContextProvider(props) {
  const meatReducer = (state, action) => {
    if (action.type === "ADD_MEAT") {
      return [...state, action.payload];
    }
    if (action.type === "REMOVE_MEAT") {
      for (var i = 0; i < state.length; i++) {
        if (state[i].id == action.payload.id) {
          console.log(state[i].id);

          state.splice(i, 1);
          console.log(state);
          
          return state;
          
        }
        
        
      }
      
    }
    
  };

  const [meatState, dispatchMeatState] = useReducer(meatReducer, []);
  const [showModal, setShowModal] = useState(false);

  if (showModal) {
    document.body.style.overflow = "hidden";
  }

  return (
    <MeatContext.Provider
      value={{
        meatState: meatState,
        dispatchMeatState: dispatchMeatState,
        showModal: showModal,
        setShowModal: setShowModal,
      }}
    >
      {props.children}
    </MeatContext.Provider>
  );
}
export default MeatContext;

Making a button to control the background image in Javascript

I’m trying to make a button you can press on the webpage that will change its background with a snow gif I prepared. I got the button to show and hide the gif and even append it, but can’t seem to make it change the full background to make it seem like it started snowing. Here’s the code for that:

function snowing(){
            let x = document.getElementById('hideimage');
            document.getElementById('sno_btn').onclick = function(){
                if (x.style.display === "none") {
                    x.style.display = "block";
                    document.body.style.backgroundImage = "url('snow.gif') no repeat scroll center";
                } else {
                    x.style.display = "none";
                    document.body.style.background = "black";
                }
        }

Right now, I just have the gif hidden on the page until I need it.
If someone can point me in the right direction, if I can achieve this with Javascript or not, or if I should be looking deeper?

I am facing problem when I am trying to fetch data from firebase. Data is successfully fetched but it is not set to Input fields after fetching

**I am facing a problem when I am trying to fetch data from firebase. Data is successfully fetched but it is not set to Input fields after fetching. Sometimes it is set but after page reloading, it gets reset. Sometimes it shows inside the input field and sometimes it is not. I am not able to find where it goes wrong. For form validation, I have used yup and Formik. I want to populate data in the input field and which is fetched from firebase.**   


import React, { useState, useRef, useEffect } from "react";   
import { auth, firebase } from "../auth/firebase";
import { Formik } from 'formik';
import * as yup from 'yup';
import { useUserAuth } from "../context/UserAuthContext";
//Funcation Component start
const ProfileDashboard = (props) => {
 //User authentication state
  const { user } = useUserAuth();
  const database = firebase.firestore();
  const [userId, setuserId] = useState(null);
  useEffect(() => {
    if (user) {
      setuserId(user.uid)
    }
  }, [])
  //Created state for store talent data which is fetched from firebase
  const [getTalentData, setTalentData] = useState([]);
  //Created state for set initial state yup fields
  const [initialValues, setintialData] = useState({
    talentName: '',
    talentDob: '',
    talentGender: ''
  })
  //To fetch data from firebase
  useEffect(() => {
    database.collection('talentsData').get()
      .then(
        response => {
          getTalentData.length = 0;
          response.docs.forEach(doc => {   
            //Store fetched data        
            getTalentData.push(doc.data());   
            console.log("Get getTalentData", getTalentData);        
          });
        })
      .then(() => {
     //After fetching data it is set to setintialData which will going to set to input field
          getTalentData.forEach((userObj) => {
            console.log("Loop Obj: ", userObj.uid);

//If user is matched then it is set to setintialData state.
if ((userObj.uid).match(userId)) {
setintialData(
{
…initialValues,
talentName: userObj.values.talentName,
talentDob: userObj.values.talentDob,
talentGender: userObj.values.talentGender
}
);
}
console.log(“Loop Init Value: “, initialValues);
})
})
.catch(error => {
console.log(“error”, error);
});
}, [userId]);

  const talName = useRef();
  const talDob = useRef();
  const talGen = useRef();
 
//This is one is validation schema
  const validationSchema = yup.object({
    talentName: yup.string()
      .max(15, 'Name should not exceed 15 Characters')
      .required('Please Enter Name'),
    talentDob: yup.string()
      .required('Please Enter DOB')
      .test(
        "DOB",
        "Please choose a valid date of birth",
        function (value) {
          console.log(value)
        }
      ),
    talentGender: yup.string()
      .required('Please Select Gender'),
  });


  return (
    <>
      <div className="profileDetailsForm">

        <Container>
          <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={(values, actions) => {
              setTimeout(() => {
                console.log(JSON.stringify(values, null, 2));
                actions.setSubmitting(false);
                firebase.firestore().collection("talentsData").add({
                  values,
                  userId
                })
                  .then(() => {
                    alert("Data save")
                  })
                  .catch((error) => {
                    alert("Error");
                  });
              }, 500);
            }}
          >
            {props => (
              <Form onSubmit={props.handleSubmit}>
                <Row>
                  <Col sm={3} className="my-1">
                    <Form.Group className="mb-3" controlId="profileName">
                      <Form.Label>Name*</Form.Label>
                      <Form.Control
                        placeholder="Name"
                        onChange={(e) => {
                          giveMeBorder(e)
                          props.handleChange(e)
                        }}
                        onBlur={props.handleBlur}
                        value={props.values.talentName}
                        name="talentName"
                      />
                      {props.errors.talentName && <span className="errorMsg">{props.errors.talentName}</span>}
                    </Form.Group>
                  </Col>

                  <Col sm={3} className="my-1">
                    <Form.Group controlId="talentDob">
                      <Form.Label>Date of Birth</Form.Label>
                      <Form.Control
                        type="date"
                        onChange={(e) => {
                          giveMeBorder(e)
                          props.handleChange(e)
                        }}
                        onBlur={props.handleBlur}
                        value={props.values.talentDob}
                        name="talentDob"
                        placeholder="Date of Birth"
                      />
                      {props.errors.talentDob && <span className="errorMsg">{props.errors.talentDob}</span>}
                    </Form.Group>
                  </Col>

                  <Col sm={3} className="my-1">
                    <Form.Label>Gender</Form.Label>
                    <Form.Select
                      aria-label="Default select example"
                      placeholder="Date of Birth"
                      ref={talGen}
                      name="talentGender"
                      type="date"
                      onChange={(e) => {
                        giveMeBorder(e)
                        props.handleChange(e)
                      }}
                      onBlur={props.handleBlur}
                      value={props.values.talentGender}
                    >
                      <option value="">Select</option>
                      <option value="female">Female</option>
                      <option value="male">Male</option>
                      <option value="transgender">Transgender</option>
                    </Form.Select>
                    {props.errors.talentGender && <span className="errorMsg">{props.errors.talentGender}</span>}
                  </Col>
                  
                </Row>
                <div className="d-flex justify-content-end">
                  <div className="profileSubmit float-right">
                    <input type="submit" />
                  </div>
                </div>
              </Form>
            )}

          </Formik>

        </Container>
      </div>
    </>
  );
};

export default ProfileDashboard;

WordPress Side Menu HTML/CSS

I am using Side Menu Lite plugin for below shown in picture buttons. I am worried about this in picture showing rectangle overlying other buttons and content. I am not able to press buttons below on slider because of this side menu.

Here is image showing above text.

#buttonfloating {
line-height: 12px;
width: 300px;
position:relative;
 top:0;
 right:0;
 margin-top: 300px;
 top:0;

}

I am worried if there is any safer way to make this button because it is not working properly. Or what I am missing here in CSS so it doesn’t take that much space.

here below is picture of this button and functions.
enter image description here

Dots navigation for slideshow

I would like to link the dots to the corresponding slide, but I have no idea how to do it with JavaScript.

The expected result: when the user click the dot, it will jump to the corresponding slide.

These code to create a slideshow is a tutorial from W3School, here.

Below is the code, please have a look and run it:

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";  
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}    
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";  
  dots[slideIndex-1].className += " active";
  setTimeout(showSlides, 2000);
}
.mySlides {
  display: none;
  background-color: green;
  color: white;
  width: 100%;
  height: 20vh;
}

.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.dot {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}
<div class="slideshow-container">

<div class="mySlides fade">
  <div class="text">Caption Text</div>
</div>

<div class="mySlides fade">
  <div class="text">Caption Two</div>
</div>

<div class="mySlides fade">
  <div class="text">Caption Three</div>
</div>

</div>

<div style="text-align:center">
  <span class="dot"></span> 
  <span class="dot"></span> 
  <span class="dot"></span> 
</div>