« first day (4934 days earlier)   

12:32 AM
@MileMijatović there either isn't a header Set-Cookie in the response headers by default, or you're using the wrong request method. If you intended to use a GET request, then that's not the issue. I think the issue is that the header doesn't exist or isn't set.
const elements = [
  { className: 'voteComment', idPrefix: 'txtVoteComment' },
  { className: 'voteYes', idPrefix: 'txtVoteYes' },
  { className: 'voteNo', idPrefix: 'txtVoteNo' },
  { className: 'voteAbstain', idPrefix: 'txtVoteAbstain' },
  { className: 'voteAbsent', idPrefix: 'txtVoteAbsent' }
];

elements.forEach((element, index) => {
  const el = input_group.querySelector(`.${element.className}`);
  el.value = '';
  el.id = `${element.idPrefix}_${index}`;
});
@Jefferson ^
 
 
3 hours later…
3:11 AM
||joke
 
A SQL query walks into a bar, walks up to two tables and asks...
'Can I join you?'
 
['hip', 'hip']
(hip hip array)
 
3:30 AM
!!towc
 
Invalid command! Did you mean: coc, wow, tomm? Try help for a list of available commands.
 
4:05 AM
||wow
 
||WOW
||coc
 
||obama James is a cool bot
Obama command no longer works.
 
 
2 hours later…
6:06 AM
Hi guys, anyone free to have a quick discussion about a doubt I have on React Suspense
 
 
1 hour later…
7:16 AM
@ParkingMaster I am trying to handle express-session from express.js app on frontend app
export const login = asyncHandler(
  async (req: Request<ILogin>, res: Response<IResponse>) => {
    const token = await UserService.authenticate(req.body);

    req.session.token = token;

    return res
      .status(200)
      .json({ success: true, message: messages.auth.loggedIn });
  }
);
I have successfully saving jwt token in MongoDB collection (sessions) by using MongoStore
// Configure session
app.use(
  session({
    name: config.session.name,
    secret: config.session.secret as string,
    resave: false,
    saveUninitialized: false,
    store,
    cookie: {
      httpOnly: isProduction,
      secure: isProduction,
      maxAge: +config.session.cookie.expiration
    }
  })
);
after successfully logging in , session for that user is saved in DB, like this

{"cookie":{"originalMaxAge":900000,"expires":"2024-04-19T07:35:27.946Z","secure":true,"httpOnly":true,"path":"/"},"token":"jwt_token_here"}
But how to use that sessionId and cookie on frontend application , to authenticate user on UI , not just on server side ?
 
7:41 AM
@ParkingMaster

this is my auth.middleware from server side app

import { NextFunction, Request, Response } from 'express';
import messages from '../assets/json/messages.json';
import { AuthenticationError } from '../errors';
import config from '../config/env';
import { verifyToken } from '../utils';

const requireAuth = async (req: Request, res: Response, next: NextFunction) => {
  try {
    if (!req.session || !req.session.token) {
      return next(new AuthenticationError(messages.auth.unauthorized));
What should I do on frontend app to use that authentication session successfully ?
 
 
4 hours later…
11:21 AM
ParkingMaster, there are subtle differences
        var b   = null;
        var c   = undefined;
        var a   = {b,c};
        alert(JSON.stringify(a));
is one such example
somewhat unrelated, in php i had to declare a variable as null to be able to reference it in the use clause of a function statement, and i try to be as consistent across programming languages as i can, ( hence i use semi colons at the end of javascript statements because it makes programming c++ easier )
something like this
        $a;
        $b=null;

        $fn=function() use (&$a,&$b){

              //$a no good
              //$b ok

        }//fn
although having said all that, i tend to only declare variables where they are actually needed and am then able to avoid situations like those, so yes i do indeed do this lol
        for(var i=0;i<10;i++){

              var a   = i*2;    //  or whatever

        }//for
it has the advantage of keeping everything that is needed in one place, so if later i wanted copy andd paste that section of code, i wouldnt have to worry about going and finding where the variables have been declared and copy that part as well
if on the other hand i were pressed on the matter, i would choose null over undefined
 
@matt Weird example because var would be declared for the entire surrounding function. An older coding style preferred all var declarations to be done at the start of the function, therefore showing this explicitly
 
yes c++ didnt even have variable hoisting, which i only had to double check explicitly recently. var, let or const, i just use var all the time unless i explicitly need let and const is just too long for me to type out hahah
 
function foo() {
    var i, a, b;
    for(i=0;i<10;i++){
        a   = i*2;    //  or whatever
    }//for

    if (someCondition) {
        b = 2 + 2;
        doSomething(b);
    }
}
^ that would be the correct way to do it with the older style
Although I seem to have mixed tabs and spaces...
 
i used to code like that
 
11:58 AM
@MileMijatović, its difficult to tell what you are actually trying to do, maybe you could include a working example using say stackblitz.com or runkit.com/home
 
12:08 PM
maybe this would help to get started runkit.com/javascript-2020/65f8e62673caa40008d1b13f
 
12:21 PM
@matt I am using server-side session management with session token saved in MongoDB
 
ok and you want to effectively use a session on the client side?
 
is it possible to use that session token on frontend app to persist state ?
 
umm yeah, you can either output the data directly into the js
or you can use a cookie that is accessible from javascript, so with httponly set not to true, then use document.cookie
 
user.service.ts

  static async authenticate(credentials: ILogin) {
    const { email, password } = credentials;
    const user = await User.getUserByEmail(email);

    if (!user) {
      throw new AuthenticationError(messages.auth.incorrectCredentials);
    }

    const passwordMatch = await verifyPassword(password, user.password);

    if (!passwordMatch) {
      throw new AuthenticationError(messages.auth.incorrectCredentials);
    }

    const token = await generateToken({ userId: user._id }, config.jwt.secret, {
auth.controller.ts

export const login = asyncHandler(
  async (req: Request<ILogin>, res: Response) => {
    const { token, user } = await UserService.authenticate(req.body);

    req.session.token = token;

    return res.status(200).json({
      success: true,
      message: messages.auth.loggedIn,
      user
    });
  }
);
 
you could even make a fetch request and return it using json
 
12:24 PM
yes, I did that
export const sendRequest = async (
  url: string,
  method: Methods,
  options: Record<string, string> = {},
  data?: any
) => {
  try {
    const response = await fetch(`${baseUrl}${url}`, {
      method,
      headers: { 'Content-Type': 'application/json' },
      ...options,
      body: JSON.stringify(data)
    });

    return await response.json();
  } catch (error: any) {
    return { message: error.message, success: false };
  }
};
but the issue is because I am using React Context
in combination with useReducer hook
everything works as expected when I am changing pages by click on the link
but when I refresh the page, the default state is loaded
import {
  createContext,
  useReducer,
  useContext,
  ReactNode,
  Dispatch
} from 'react';

const LOGIN = 'LOGIN';
const LOGOUT = 'LOGOUT';

interface IUser {
  firstName: string;
  lastName: string;
  birthDate: Date;
  email: string;
  password: string;
  image: string;
}

type AuthState = {
  isAuthenticated: boolean;
  user: IUser | null;
};

type AuthProviderProps = {
  children: ReactNode;
};

type AuthAction =
  | { type: 'LOGIN'; payload: { user: IUser } }
  | { type: 'LOGOUT' };

const authReducer = (state: AuthState, action: AuthAction) => {
and I am getting

isAuthenticated: false,
user: null,
instead of isAuthenticated: true and user: { .... }
Is there any way to make a state persistent after page refresh ?
 
i am not familiar with react, i work with single page web apps, so we dont do changing pages, but it seems you are not updating something serverside when you perform your sendrequest
 
12:48 PM
React is also spa
Single page app
 
1:49 PM
 
2:30 PM
@Feeds :
1. All of them
2. It depends
3. Lake Eyre
4. Jaws (1975)
5. 8 Planets
6. All of them
7. Boeing (777X)
8. Yes (5+5=10)
9. Perth
10. Everyone who plays drums
 
 
1 hour later…
3:52 PM
@ParkingMaster what about the bonus question? the one that appear when you hover and stay on the image)
 
@VagifVALIYEV Welcome to the JavaScript chat! Please review the room rules. If you have a question, just post it, and if anyone's free and interested they'll help. If you want to report an abusive user or a problem in this room, visit our meta.
 

« first day (4934 days earlier)