I kept my json file at public folder but while trying to fetch values shown undefined [closed]

My Folder structure is like the image

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

const { data: reviews } = useQuery('reviews', () => fetch("reviews.json").then(res => res.json()))

How can I make a different text based on the user’s choices?

I’m making a Tic Tac Toe game where the user can choose if they play X or O. How do I change the onclick function to display X if they chose X, or O if they chose O?

My code right now doesn’t work since it only displays X even if I selected O from the two buttons.

Note: The other boxes don’t have a function yet. To see the problem I’m talking about, click the first box on the upper left.

@import url('https://fonts.googleapis.com/css2?family=Koulen&family=VT323&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Lobster&family=Signika+Negative:wght@400;500;600&display=swap');
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html, body {
    text-align: center;
    background-color: #1C2C54;
    color: #D175B7;
    font-family: 'Signika Negative', sans-serif;
}

main {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    gap: 20px;
    margin: auto;
    position: absolute;
    top: 50%;
    bottom: 50%;
    left: 50%;
    right: 50%;
    
}

h1 {
    font-family: 'VT323', monospace;
    font-size: 3rem;
}

.text-container {
    display: flex;
    flex-direction: column;
    width: 300px;
}

.grid-container {
    display: grid;
    grid-template-columns: auto auto auto;
    background-color: #4BC3B5;
    padding: 20px;
    
  }
  .grid-item {
    background-color: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(0, 0, 0, 0.8);
    padding: 30px;
    font-size: 30px;
    text-align: center;
    cursor: pointer;
  }

.button-container {
    display: flex;
    flex-direction: row;
    gap: 10px;
}

button {
    padding: 3px 20px;
    background-color: #4BC3B5;
    color: white;
    border: 3px solid #34a396;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #2c8d82;
    border: 3px solid #124640;
}

button:focus {
    background-color: #2c8d82;
    border: 3px solid #124640;
}

  .score-container {
      display: flex;
      flex-direction: column;
      gap: 10px;
      width: 300px;
      justify-content: center;
      color: white;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tic Tac Toe</title>
</head>
<body>
    <main>
        <div class="text-container">
            <h1>Tic Tac Toe</h1>
        </div>
        <div class="grid-container">
            <div class="grid-item" id="grid1" onclick="clickBox1()"></div>
            <div class="grid-item" id="grid2" onclick="clickBox2()" ></div>
            <div class="grid-item" id="grid3" onclick="clickBox3()"></div>
            <div class="grid-item" id="grid4" onclick="clickBox4()"></div>
            <div class="grid-item" id="grid5" onclick="clickBox5()"></div>
            <div class="grid-item" id="grid6" onclick="clickBox6()"></div>
            <div class="grid-item" id="grid7" onclick="clickBox7()"></div>
            <div class="grid-item" id="grid8" onclick="clickBox8()"></div>
            <div class="grid-item" id="grid9" onclick="clickBox9()"></div>
        </div>
        <div class="button-container">
            <button id="x-el" onclick="selectX()">X</button>
            <button id="o-el" onclick="selectO()">O</button>
        </div>
        <div class="score-container">
            <p id="playerscore">Player Score:</p>
            <p id="compscore">Computer Score:</p>
        </div>
    </main>
    <script>
        // Grab the elements
        let xBtn = document.getElementById('x-el')
        let oBtn = document.getElementById('o-el')
        let playerScoreDisplay = document.getElementById('playerscore')
        let compScoreDisplay = document.getElementById('compscore')
        let x = 'X'
        let o = 'O'

        // Grabbing individual boxes
        let box1 = document.getElementById('grid1');
        let box2 = document.getElementById('grid2');
        let box3 = document.getElementById('grid3');
        let box4 = document.getElementById('grid4');
        let box5 = document.getElementById('grid5');
        let box6 = document.getElementById('grid6');
        let box7 = document.getElementById('grid7');
        let box8 = document.getElementById('grid8');
        let box9 = document.getElementById('grid9');

/*
        let boxes = document.querySelectorAll("div.grid-item")
        */

        // Selecting x or o
        function selectX() {
            alert('You selected X!');
        }
        function selectO() {
            alert('You selected O!');
        }

        // Function for each box
        function clickBox1() {
            if (selectX) {
                box1.innerHTML = x;
            } else if (selectO) {
                box1.innerHTML = o;
            }
        }
        
        

    </script>
</body>
</html>

Condition Ternary Operation in React [closed]

I have a problem using ternary condition in my react app.
I actually have 4 conditions and sometimes it outputs the wrong one.

First if product have status of “Linked” and “Existing”
Second if product have status of all “Existing”
Third if product have status of all “Linked”
Fourth if neither of them all.

  const productExistingAndLinked = product?.some(
    (e) => e?.status === 'Linked' && e?.status === 'Existing'
  ),
  const productExisting = product?.every(
    (e) => e?.status === 'Existing'
  ),
  const productLinked = product?.every(
    (e) => e?.status === 'Linked'
  ),

<div>
  {productExistingAndLinked ? (
    <div>Linked and Existing</div>
  ) : productExisting ? (
    <div
    >
      All Existing
    </div>
  ) : productLinked ? (
    <div>
      All Linked
    </div>
  ) : (
    <div>All Unlinked</div>
  )}

</div>

Class syntax in javascript and OOP paradigm [duplicate]

Ok so i was yesterday doing the freeCodeCamp Javascript Course and there is a part when the exercise says:

It should be noted that the class syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc

so my question is, how about that? what does it means that the js doesnt have the implementation of the paradigm OOP?

randomize items in an array and keep original order

I would like to randomize the email addresses that are being output and remove duplicates and have them retain the original order. This works perfectly fine when I do not randomize. I generate the emails, remove dups, and output and have no issues. I also have no issues randomizing. The issue I seem to have is combining the two. Being able to generate the array, randomize, remove dups AND retain the original order. Below is what I have tried already, this is the closest I have gotten. Thanks for any help.

function randomize(arr) {
    var i, j, tmp;
    for (i = arr.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    return arr;
}
const sourceArray = [];

var arr = sourceArray;

// we start with an empty source array
// const sourceArray = [];

// the number of emails / 2
const numberOfEmails = 100000;

// first pass we add 100,000 emails
for (let index = 0; index < numberOfEmails; index++) {
  sourceArray.push(`test${index}@google.com`);
}

// second pass we create dupes for all of them
for (let index = 0; index < numberOfEmails; index++) {
  sourceArray.push(`test${index}@google.com`);
}

// throw in some extra dupes for fun
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);
sourceArray.push(`[email protected]`);

// this serves as a map of all email addresses that we want to keep
const map = {};

// an exact time before we run the algorithm
const before = Date.now();

// checks if the email is in the hash map
const isInHashmap = (email: string) => {
  return map[email];
};

// iterate through all emails, check if they are in the hashmap already, if they are we ignore them, if not we add them.
sourceArray.forEach((email) => {
  if (!isInHashmap(email)) {
    map[email] = true;
  }
});

// we fetch all keys from the hashmap
const result = Object.keys(map);

arr = randomize(arr);

console.log(`Randomized here: ${sourceArray}`);

console.log(`The count after deduplicating: ${result.length}`);

// gets the time expired between starting and completing deduping
const time = Date.now() - before;

console.log(`The time taken: ${time}ms`);

console.log(result);

Wanted help in understanding how parameters are defined in Callback functions, using this example (if possible)

I am trying to understand more on how callback functions work in JavaScript.

I found this simple example code online and after adding the imports & additional txt file it’s working. However I am not sure why it is working as the parameters of the functions aren’t being defined anywhere?

fs.readFile(`${__dirname}/temp.txt`, (err, data) => {
console.log(`Breed: ${data}`);
superagent.get(`https://dog.ceo/api/breed/${data}/images/random`).end((err,res) =>{
    console.log(res.body)
}); })

Upon running this I get the expected result on the console with the line displaying Breed: ${data} and the next line showing the body of the res.

However, the err, data parameters have never been provided to the arrow function within readFile. Neither has the err,res parameters ever been called/provided a value for it to display a message to the console, then how are these lines displaying a message to the console?

I could have understood this working if .readFile returned a err and data value & .end returned a err and res value, however upon reading the documentation both these functions return void, thus i’m confused and help would be appreciated.

Pause and resume a timer (setTimeout) [duplicate]

I made a simple calculator application and there is one key functionality that I am still missing: having my timer paused when the pause button is clicked and then resumed whenever it’s clicked again.

Here is my code:

const hourCount = document.querySelector(".hour-count"),
            minuteCount = document.querySelector(".minute-count"),
            secondCount = document.querySelector(".second-count");
      milisecondCount = document.querySelector(".milisecond-count");

function setTimer() {

    let hours = 0,
        minutes = 0,
        seconds = 0;
      miliseconds = 0;
  let interval = 50;
      
  let timer = setTimeout(function exec() {
    miliseconds += 50;
    milisecondCount.textContent = miliseconds < 1000 ? `0${miliseconds}` : miliseconds;
  
    if (miliseconds === 1000) {
        miliseconds = 0;
        secondCount.textContent = ++seconds < 10 ? `0${seconds}` : seconds;
    }
    
    if (seconds === 60) {
        seconds = 0;
        minuteCount.textContent = ++minutes < 10 ? `0${minutes}` : minutes;
    }
    
    if (minutes === 60) {
      minutes = 0;
      hourCount.textContent = ++hours < 10 ? `0${hours}` : hours;
    }
  
    timer = setTimeout(exec, interval);
  }, interval);
  
  setTimer.pause = () => {
    clearTimeout(timer);
  };
  
  setTimer.reset = () => {
    clearTimeout(timer)
    
    hourCount.textContent = "00";
    minuteCount.textContent = "00";
    secondCount.textContent = "00";
    milisecondCount.textContent = "0000";
  }
}

const start = document.querySelector(".start"),
            pause = document.querySelector(".pause"),
            reset = document.querySelector(".reset");
      
start.addEventListener("click", () => setTimer()); 
pause.addEventListener("click", () => setTimer.pause());
reset.addEventListener("click", () => setTimer.reset());
:is(.hour-count, .minute-count, .second-count)::after {
  content: ":";
}
<p class="clock-timer">
  <span class="hour-count">00</span><span class="minute-count">00</span><span class="second-count">00</span><span class="milisecond-count">0000</span>
</p>

<button class="start">Start</button>
<button class="pause">Pause</button>
<button class="reset">Reset</button>

At the moment the pause button already pauses the timer by using clearTimeout() but it sets the miliseconds back to 0 which I would like to avoid.

Firebase query() with condition ( Version 9 web ) [duplicate]

  let q = query(
            collection(dbFirebase, "users"),
            where("uid", "!=", id),
            orderBy("uid"),
            limit(1)
        )
        if (lastVisible) {
            q = q.startAfter(lastVisible)
        }

I just want to add condition for the query ‘startAfter’ if i don’t have value ( lastVisible ).

If i don’t have value (lastVisible), my request is good.

If i have a value (lastVisible), I have an error.

My error : Error TypeError: q.startAfter is not a function

Thanks for help.

JSON: Bad String

I’m trying to create a JSONBlob with this JSON:

{
    "res": "<!DOCTYPE html><html lang='en'> <head> <meta charset='UTF-8'/> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'/> <meta name='viewport' content='width=device-width'/> <meta name='ad.size' content='width=300,height=250'/> <title>Banner</title> <style>*{box-sizing: border-box;}body{margin: 0; padding: 0;}.hide{display: none;}#banner{width: 300px; height: 250px; position: relative; overflow: hidden; -webkit-transition: background-color 200ms linear; -ms-transition: background-color 200ms linear; transition: background-color 200ms linear;}[class^='scene']{display: none; width: 300px; height: 250px; position: absolute; top: 0; left: 0; overflow: hidden;}[class^='scene'] > div, [class^='scene'] > img{position: absolute;}.scene0{background-color: #9719d7;}.scene0 .logo{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: 0px 0px; width: 223px; height: 179px; right: 0; top: 35px;}.scene0 .fee{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -228px -61px; width: 127px; height: 49px; top: 100px; left: 30px;}.scene0 .gone{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -228px -180px; width: 101px; height: 43px; top: 104px; left: 170px;}.scene0 .dolar{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -360px -61px; width: 23px; height: 49px; top: 100px; left: 30px;}.scene0 .l_5{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -388px -61px; width: 23px; height: 43px; top: 104px; left: 55px;}.scene0 .l_f{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -360px -180px; width: 20px; height: 42px; top: 104px; left: 90px;}.scene0 .l_e1{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -334px -180px; width: 21px; height: 42px; top: 104px; left: 112px;}.scene0 .l_e2{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -334px -180px; width: 21px; height: 42px; top: 104px; left: 135px;}.scene0 .hand{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: 0px -184px; width: 128px; height: 254px; top: 165px; left: -70px;}.scene1 .cover{background-color: #da1710; width: 300px; height: 250px;}.scene1 .purple_stripe{width: 12px; height: 250px; background-color: #9719d7;}.scene1 .logo_w{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -364px -142px; width: 41px; height: 18px; left: 25px; top: 20px;}.scene1 .title{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -228px -115px; width: 188px; height: 22px; left: 25px; top: 55px;}.scene1 .copy{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -228px 0px; width: 191px; height: 56px; left: 25px; top: 90px;}.scene1 .cta{background-image: url(https://i.ibb.co/D8VJz1g/sprites.png); background-position: -228px -142px; width: 131px; height: 33px; left: 25px; top: 180px;}.chopper{position: absolute; top: -600px; left: -850px;}</style> <script type='text/javascript'>var clickTag='https://www.google.com.au'; </script> </head> <body> <a href='javascript:window.open(window.clickTag)'> <div id='banner'> <div class='scene0'> <div class='logo'></div><div class='fee'></div><div class='gone'></div><div class='dolar'></div><div class='l_5'></div><div class='l_f'></div><div class='l_e1'></div><div class='l_e2'></div><div class='hand'></div></div><div class='scene1'> <div class='cover'></div><div class='purple_stripe'></div><div class='logo_w'></div><div class='title'></div><div class='copy'></div><div class='cta'></div></div><div class='chopper'> <svg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' width='2002.5' height='2002.5' viewBox='0 0 2002.5 2002.5' > <defs> <mask id='maskR1'> <circle id='pie1' cx='1001.25' cy='1001.25' r='1000' style=' stroke: #ffffff; stroke-miterlimit: 10; stroke-width: 2000px; '/> </mask> <mask id='maskP1'> <circle id='pie2' cx='1001.25' cy='1001.25' r='1000' style=' stroke: #ffffff; stroke-miterlimit: 10; stroke-width: 2000px; '/> </mask> <mask id='maskP2'> <circle id='pie3' cx='1001.25' cy='1001.25' r='1000' style=' stroke: #ffffff; stroke-miterlimit: 10; stroke-width: 2000px; '/> </mask> </defs> <g mask='url(#maskR1)'> <circle id='pieChange1' cx='1001.25' cy='1001.25' r='1000' style=' stroke: #990000; stroke-miterlimit: 10; stroke-width: 2000px; '/> </g> <g mask='url(#maskP1)'> <circle id='pieChange2' cx='1001.25' cy='1001.25' r='1000' style=' stroke: #ff1fdd; stroke-miterlimit: 10; stroke-width: 2000px; '/> <g id='logoChange2'> <path d='M920.51,749.28c9,0,14.86,3.26,18.34,14.85h0L963.35,840s3.79,10.11,7.25,10.73H922.36c-9,0-16.91-5-19.44-14.6h0l-22-76.19s-2.37-9.2-6-10.65h45.51Zm204.49,0c-3.58,1.45-6,10.65-6,10.65l-22,76.19c-2.54,9.56-10.46,14.6-19.44,14.6H1029.4c3.45-.62,7.24-10.73,7.24-10.73l24.52-75.86c3.46-11.59,9.34-14.85,18.32-14.85Zm-97.83,0V850.72H972.83V749.28Z' transform='translate(1.25 -70)' style='fill: #da1710; fill-rule: evenodd'/> </g> </g> <g mask='url(#maskP2)'> <circle id='pieChange3' cx='1001.25' cy='1001.25' r='1000' style=' stroke: #991ad6; stroke-miterlimit: 10; stroke-width: 2000px; '/> <g id='logoChange3'> <path d='M920.51,749.28c9,0,14.86,3.26,18.34,14.85h0L963.35,840s3.79,10.11,7.25,10.73H922.36c-9,0-16.91-5-19.44-14.6h0l-22-76.19s-2.37-9.2-6-10.65h45.51Zm204.49,0c-3.58,1.45-6,10.65-6,10.65l-22,76.19c-2.54,9.56-10.46,14.6-19.44,14.6H1029.4c3.45-.62,7.24-10.73,7.24-10.73l24.52-75.86c3.46-11.59,9.34-14.85,18.32-14.85Zm-97.83,0V850.72H972.83V749.28Z' transform='translate(1.25 -70)' style='fill: #da1710; fill-rule: evenodd'/> </g> </g> </svg> </div></div></a> <script src='https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js'></script> <script>!function(e,t){'object'==typeof exports&&'undefined'!=typeof module?t(exports):'function'==typeof define&&define.amd?define(['exports'],t):t((e=e||self).window=e.window||{})}(this,function(e){'use strict';function i(){return'undefined'!=typeof window}function j(){return a||i()&&(a=window.gsap)&&a.registerPlugin&&a}function m(e){return Math.round(1e4*e)/1e4}function n(e){return parseFloat(e)||0}function o(e,t){var r=n(e);return~e.indexOf('%')?r/100*t:r}function p(e,t){return n(e.getAttribute(t))}function r(e,t,r,i,s,o){return P(Math.pow((n(r)-n(e))*s,2)+Math.pow((n(i)-n(t))*o,2))}function s(e){return console.warn(e)}function t(e){return'non-scaling-stroke'===e.getAttribute('vector-effect')}function w(e){if(!(e=v(e)[0]))return 0;var n,i,o,a,f,h,d,l=e.tagName.toLowerCase(),u=e.style,c=1,g=1;t(e)&&(g=e.getScreenCTM(),c=P(g.a*g.a+g.b*g.b),g=P(g.d*g.d+g.c*g.c));try{i=e.getBBox()}catch(e){s('Some browsers wont measure invisible elements (like display:none or masks inside defs).')}var _=i||{x:0,y:0,width:0,height:0},y=_.x,w=_.y,x=_.width,m=_.height;if(i&&(x||m)||!k[l]||(x=p(e,k[l][0]),m=p(e,k[l][1]),'rect'!==l&&'line'!==l&&(x*=2,m*=2),'line'===l&&(y=p(e,'x1'),w=p(e,'y1'),x=Math.abs(x-y),m=Math.abs(m-w))),'path'===l)a=u.strokeDasharray,u.strokeDasharray='none',n=e.getTotalLength()||0,c!==g&&s('Warning: <path> length cannot be measured when vector-effect is non-scaling-stroke and the element isnt proportionally scaled.'),n*=(c+g)/2,u.strokeDasharray=a;else if('rect'===l)n=2*x*c+2*m*g;else if('line'===l)n=r(y,w,y+x,w+m,c,g);else if('polyline'===l||'polygon'===l)for(o=e.getAttribute('points').match(b)||[],'polygon'===l&&o.push(o[0],o[1]),n=0,f=2;f<o.length;f+=2)n+=r(o[f-2],o[f-1],o[f],o[f+1],c,g)||0;else'circle'!==l&&'ellipse'!==l||(h=x/2*c,d=m/2*g,n=Math.PI*(3*(h+d)-P((3*h+d)*(h+3*d))));return n||0}function x(e,t){if(!(e=v(e)[0]))return[0,0];t=t||w(e)+1;var r=h.getComputedStyle(e),i=r.strokeDasharray||'',s=n(r.strokeDashoffset),o=i.indexOf(',');return o<0&&(o=i.indexOf(' ')),t<(i=o<0?t:n(i.substr(0,o)))&&(i=t),[-s||0,i-s||0]}function y(){i()&&(h=window,l=a=j(),v=a.utils.toArray,d=-1!==((h.navigator||{}).userAgent||'').indexOf('Edge'))}var a,v,h,d,l,b=/[-+=.]*d+[.e-+]*d*[e-+]*d*/gi,k={rect:['width','height'],circle:['r','r'],ellipse:['rx','ry'],line:['x2','y2']},P=Math.sqrt,f={version:'3.6.0',name:'drawSVG',register:function register(e){a=e,y()},init:function init(e,r){if(!e.getBBox)return!1;l||y();var i,s,a,f=w(e);return this._style=e.style,this._target=e,r+''=='true'?r='0 100%':r?-1===(r+'').indexOf(' ')&&(r='0 '+r):r='0 0',s=function _parse(e,t,n){var r,i,s=e.indexOf(' ');return i=s<0?(r=void 0!==n?n+'':e,e):(r=e.substr(0,s),e.substr(s+1)),r=o(r,t),(i=o(i,t))<r?[i,r]:[r,i]}(r,f,(i=x(e,f))[0]),this._length=m(f),this._dash=m(i[1]-i[0]),this._offset=m(-i[0]),this._dashPT=this.add(this,'_dash',this._dash,m(s[1]-s[0])),this._offsetPT=this.add(this,'_offset',this._offset,m(-s[0])),d&&(a=h.getComputedStyle(e)).strokeLinecap!==a.strokeLinejoin&&(s=n(a.strokeMiterlimit),this.add(e.style,'strokeMiterlimit',s,s+.01)),this._live=t(e)||~(r+'').indexOf('live'),this._props.push('drawSVG'),1},render:function render(e,t){var n,r,i,s,o=t._pt,a=t._style;if(o){for(t._live&&(n=w(t._target))!==t._length&&(r=n/t._length,t._length=n,t._offsetPT.s*=r,t._offsetPT.c*=r,t._dashPT?(t._dashPT.s*=r,t._dashPT.c*=r):t._dash*=r);o;)o.r(e,o.d),o=o._next;i=t._dash||e&&1!==e&&1e-4||0,n=t._length-i+.1,s=t._offset,i&&s&&i+Math.abs(s%t._length)>t._length-.2&&(s+=s<0?.1:-.1)&&(n+=.1),a.strokeDashoffset=i?s:s+.001,a.strokeDasharray=n<.2?'none':i?i+'px,'+n+'px':'0px, 999999px'}},getLength:w,getPosition:x};j()&&a.registerPlugin(f),e.DrawSVGPlugin=f,e.default=f;if (typeof(window)==='undefined'||window!==e){Object.defineProperty(e,'__esModule',{value:!0})}else{delete e.default}}); </script> <script>(function (){window.onload=function (){initBanner();}; function initBanner(){gsap.registerPlugin(DrawSVGPlugin); tl=new TimelineLite({repeat: 2, repeatDelay: 2, onComplete: function (){},}); TweenLite.defaultEase=Cubic.easeInOut; showFrames(tl);}function generateFrame0(){var tl=new TimelineLite(); tl.addLabel('startf0'); tl.add( TweenLite.to('.hand', 0.25,{x: -10, y: -90, ease: 'none'}), 'startf0+=.5' ); tl.add( TweenLite.to('.hand', 0.25,{x: 40, y: -10, ease: 'none'}), '>' ); tl.add( TweenLite.to('.dolar', 0.35,{autoAlpha: 0, ease: 'none'}), '<' ); tl.add( TweenLite.to('.l_5', 0.35,{autoAlpha: 0, ease: 'none'}), '<' ); tl.add( TweenLite.to('.hand', 0.25,{x: 30, y: -90, ease: 'none'}), '>' ); tl.add( TweenLite.to('.hand', 0.25,{x: 65, y: -10, ease: 'none'}), '>' ); tl.add( TweenLite.to('.l_f', 0.35,{autoAlpha: 0, ease: 'none'}), '<' ); tl.add( TweenLite.to('.hand', 0.25,{x: 75, y: -90, ease: 'none'}), '>' ); tl.add( TweenLite.to('.hand', 0.45,{x: 115, y: 90, ease: 'none'}), '>' ); tl.add( TweenLite.to('.l_e1', 0.25,{autoAlpha: 0, ease: 'none'}), '<' ); tl.add( TweenLite.to('.l_e2', 0.25,{autoAlpha: 0, ease: 'none'}), '<' ); return tl;}function generateChopper(){gsap.set('circle',{transformOrigin: 'center center'}); var tl=new TimelineLite(); tl.addLabel('startChopper'); tl.add( TweenLite.fromTo( '#pie1', 3,{rotation: '-180', drawSVG: '0%', ease: 'sine.inOut'},{rotation: '0', drawSVG: '50%', ease: 'sine.inOut'}), 'startChopper+=.5' ); tl.add( TweenLite.fromTo( '#pie2', 3,{rotation: '-180', drawSVG: '0%', ease: 'sine.inOut'},{rotation: '0', drawSVG: '50%', ease: 'sine.inOut'}), 'startChopper+=.8' ); tl.add( TweenLite.to('#logoChange2', 1.5,{scale: 0.9, transformOrigin: 'center center', ease: 'sine.inOut',}), 'startChopper+=1.5' ); tl.add( TweenLite.fromTo( '#pie3', 3,{rotation: '-180', drawSVG: '0%', ease: 'sine.inOut'},{rotation: '0', drawSVG: '50%', ease: 'sine.inOut'}), 'startChopper+=1.1' ); tl.add( TweenLite.fromTo( '#logoChange3', 1.5,{scale: 0.8, transformOrigin: 'center center', ease: 'sine.inOut',},{scale: 0.6, ease: 'sine.inOut'}), 'startChopper+=2' ); return tl;}function generateFrame1(){var tl=new TimelineLite(); tl.addLabel('startf1'); tl.add( TweenLite.from('.cover', 1,{autoAlpha: 0, ease: Strong.easeInOut,}), 'startChopper-=.5' ); tl.add( TweenLite.from('.purple_stripe', 1,{autoAlpha: 0, ease: Strong.easeInOut,}), '<' ); tl.add( TweenLite.from('.logo_w', 1,{autoAlpha: 0, ease: Strong.easeInOut,}), '<' ); tl.add( TweenLite.from('.title', 1,{autoAlpha: 0, ease: Strong.easeInOut,}), '<' ); tl.add( TweenLite.from('.copy', 1,{autoAlpha: 0, ease: Strong.easeInOut,}), '<' ); tl.add( TweenLite.from('.cta', 1,{autoAlpha: 0, ease: Strong.easeInOut}), '<' ); return tl;}function showFrames(tl){var addedtime=0.3; var frameInterval=1.5 + addedtime; var aniSpeed=1.5, aniSpeedSlow=aniSpeed + 0.5, aniSpeedFast=aniSpeed - 0.5; var loopInterval=2; tl.add('FrameStart0'); tl.add(generateFrame0(), 'FrameStart0+=.5'); tl.add('FrameStartChopper'); tl.add(generateChopper()); tl.add('FrameStart1'); tl.add(generateFrame1(), 'FrameStart1-=2.2'); document.getElementsByClassName('scene0')[0].style.display='block'; document.getElementsByClassName('scene1')[0].style.display='block';}})(); </script> </body></html>"
}

The value to the res key is a compiled HTML string that I have to use on the frontend as an iframe‘s srcdoc like I’ve done in this StackBlitz sample.

But for some reason it’s not being considered as a valid string in the context of JSON.

I tried:

  1. Linting the JSON using JSONLint but that errors out with the error:

    Error: Parse error on line 2:
    { “res”: “<htm
    ———^
    Expecting ‘STRING’, ‘NUMBER’, ‘NULL’, ‘TRUE’, ‘FALSE’, ‘{‘, ‘[‘, got ‘undefined’

  2. Checking whether it can be stringifyed using JSON.stringify without any errors.

  3. Checking the type of the compiled html string using typeof and that’s string too.

  4. Checking JSON Bad String Error but not sure what the issue is, with my string and how can I figure out at what point is the string not correct.

I’m also curious why a valid string in JavaScript‘s context is not being considered valid in the context of JSON. Am I missing something here?

Property ‘_id’ does not exist on type. Getting type error when trying to access property _id on result of a promise in nestjs application

In my nest application I am getting type error when calling _id on user because mongoose defines the _id automatically & therefore its not present in my schema which is defined as type for the promise.

When the promise type is changed to any like Promise<any> then there is no type error.

async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }

but I want to know is this the correct way or I should be doing something else.
I do not want to define _id in schema to solve this issue.

 @Prop({ auto: true})
 _id!: mongoose.Types.ObjectId;

user.schema.ts

// all the imports here....

export type UserDocument = User & Document;

@Schema({ timestamps: true })
export class User {

  @Prop({ required: true, unique: true, lowercase: true })
  email: string;

  @Prop()
  password: string;

}

export const UserSchema = SchemaFactory.createForClass(User);   

users.controller.ts

@Controller('users')
@TransformUserResponse(UserResponseDto)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto) {
      const user = await this.usersService.create(createUserDto);
      return user._id;
  }

}

users.service.ts

// all the imports here....  
   
@Injectable()
export class UsersService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }
}

Logout All sessions for an account in express-session, postgresql (connect-pg-simple)

I was wondering how one would create a route to logout all sessions (not just the current one) for a user when using express-session and connect-pg-simple as a session store.

I have the sessions table name set as user_sessions and have previously been able to achieve this using the mysql store on a previous project, which went something like this;

const db = require("../db/connection");

exports.logoutAllDevices = async (user_id) => {
// req.logout(); -- I called this in the controller just before, left it here to show its been called
let logoutAllQuery = 'DELETE FROM user_sessions WHERE JSON_EXTRACT(`data`, "$.passport.user") = $1;';
await db.query(logoutAllQuery, [user_id]);
return;
};

which i found before and the idea was to destroy all sessions related to that user as well as calling the req.logout() function.

However, I can’t get any solution to work with this postgres store. Help is appreciated.

reactjs redux – user is null

I dont know why when i try to fetch data from api using redux (i can see the data in when i mapstatetoprops ) but this error (user is null ) message show up when i try to display data to user.
this is a screenshot shown the user is null error
I call the dispatch from componentDidMount react, i think its the right place to call api,

this is my code :

import React, { Component } from 'react';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { connect } from 'react-redux';
import store from './state/store';
import { loadUser } from './state/actions/auth/authActions';

//pages
import Login from './app/auth/Login';
import Wrapper from './wrapper/Wrapper';

class App extends Component {

  componentDidMount() {
    store.dispatch(loadUser());
  }

  render() {
    const { token, user, isLoading } = this.props.auth
    return (
      <Router>
        <Routes>
          <Route path='/login' element={<Login />} />
          <Route path='/' element={token ? <Wrapper user={user._id} isLoading={isLoading}></Wrapper> : <Login />} />
        </Routes>
      </Router>
    )
  }
}

const mapStateToProps = state => {
  return {
    auth: state.auth
  }
}

export default connect(mapStateToProps, { loadUser })(App);