I am not able to click on the element in javascript playwright

i am doing below to click

await this.page.getByRole(‘tab’, { name: “‘”+statusHolder+”‘”}).click();

i am getting error message
waiting for getByRole(‘tab’, { name: ”Plan trip/buy tickets” })

if i hardcode this it works fine.

await this.page.getByRole(‘tab’, { name: ‘Plan trip/buy tickets’}).click();

in the error it is appending extra at the end.

await this.page.getByRole(‘tab’, { name: “‘”+statusHolder+”‘”}).click();

await this.page.getByRole(‘tab’, { name: ‘Plan trip/buy tickets’}).click();

how can i paramterized the get by role in javascript playwright.

Why is my left arrow not working accordingly to my logic?

I want to create a canvas spinner that lets me create illusions of 3d models, so each angel means a different key frame to navigate through different angels with the arrows on the bottom. Somehow iam not getting the eft arrow to work correctly, does anyone see an issue on that logic

https://amaranth-alyse-50.tiiny.site

document.getElementById('setKeyframeButton').addEventListener('click', () => {
    if (currentFrameIndex >= 0 && !keyframeIndices.includes(currentFrameIndex)) {
        keyframeIndices.push(currentFrameIndex);
        keyframeIndices.sort((a, b) => a - b);
        updateKeyframesList();
        currentKeyframeIndex = keyframeIndices.indexOf(currentFrameIndex);
    }
});

document.getElementById('speedInput').addEventListener('input', (event) => {
    switchSpeed = parseInt(event.target.value, 10);
});

document.getElementById('nextButton').addEventListener('click', () => {
    if (isPlayingKeyframes) return;
    handleNextFrame();
});

document.getElementById('prevButton').addEventListener('click', () => {
    if (isPlayingKeyframes) return;
    handlePrevFrame();
});

function sortAndAssignIndices() {
    frames = frames.map((frameObj, index) => ({
        ...frameObj,
        fileName: frameFiles[index]
    })).sort((a, b) => extractNumber(a.fileName) - extractNumber(b.fileName));

    frames.forEach((obj, index) => {
        obj.index = index;
    });

    frameFiles = frames.map(obj => obj.fileName);
    updateFrameList();
}

function extractNumber(fileName) {
    const match = fileName.match(/d+/);
    return match ? parseInt(match[0], 10) : 0;
}

function updateFrameList() {
    const frameList = document.getElementById('frames');
    frameList.innerHTML = '';

    frames.forEach((frameObj) => {
        addFrameToList(frameObj.src, frameObj.fileName, frameObj.index);
    });
}

function addFrameToList(frameSrc, fileName, index) {
    const frameList = document.getElementById('frames');
    const li = document.createElement('li');
    li.draggable = true;
    li.dataset.index = index;
    li.innerHTML = `
        <img src="${frameSrc}" alt="Frame">
        <span>${fileName}</span>
    `;

    li.addEventListener('click', () => {
        updateFrame(index);
    });

    li.addEventListener('dragstart', handleDragStart);
    li.addEventListener('dragover', handleDragOver);
    li.addEventListener('drop', handleDrop);
    li.addEventListener('dragend', handleDragEnd);

    frameList.appendChild(li);
}

function updateKeyframesList() {
    const keyframeList = document.getElementById('keyframes');
    keyframeList.innerHTML = '';
    keyframeIndices.forEach((index) => {
        const frameObj = frames[index];
        addKeyframeToList(frameObj.src, frameObj.fileName, frameObj.index);
    });
}

function addKeyframeToList(keyframeSrc, fileName, index) {
    const keyframeList = document.getElementById('keyframes');
    const li = document.createElement('li');
    li.draggable = true;
    li.dataset.index = index;
    li.innerHTML = `
        <img src="${keyframeSrc}" alt="Keyframe">
        <span>${fileName}</span>
    `;

    li.addEventListener('dragstart', handleDragStart);
    li.addEventListener('dragover', handleDragOver);
    li.addEventListener('drop', handleDrop);
    li.addEventListener('dragend', handleDragEnd);

    keyframeList.appendChild(li);
}

function handleNextFrame() {
    let nextKeyframeIndex = getNextKeyframeIndex();
    if (nextKeyframeIndex !== -1) {
        currentKeyframeIndex = keyframeIndices.indexOf(nextKeyframeIndex);
        displayFramesBetweenOrOutside(currentFrameIndex, nextKeyframeIndex);
    }
}

function handlePrevFrame() {
    let prevKeyframeIndex = getPrevKeyframeIndex();
    if (prevKeyframeIndex !== -1) {
        currentKeyframeIndex = keyframeIndices.indexOf(prevKeyframeIndex);
        if (currentKeyframeIndex === -1) {
            // If currentKeyframeIndex is not valid, determine the index of the previous keyframe
            currentKeyframeIndex = keyframeIndices.indexOf(prevKeyframeIndex);
        }
        if (currentFrameIndex === keyframeIndices[0]) {
            // If at the first keyframe, loop to the last keyframe and display frames in reverse order
            displayFramesBetweenOrOutside(currentFrameIndex, keyframeIndices[keyframeIndices.length - 1], true);
        } else {
            // Display frames in reverse between keyframes
            displayFramesBetweenOrOutside(currentFrameIndex, prevKeyframeIndex, true);
        }
    }
}

function displayFramesBetweenOrOutside(currentIndex, targetIndex, isReverse = false) {
    if (keyframeIndices.length < 2) {
        updateFrame(targetIndex);
        return;
    }

    const framesToDisplay = [];
    const startIndex = isReverse ? targetIndex : currentIndex;
    const endIndex = isReverse ? currentIndex : targetIndex;

    if (startIndex < endIndex) {
        for (let i = startIndex + 1; i < endIndex; i++) {
            framesToDisplay.push(frames[i]);
        }
    } else {

        if (isReverse) {
            for (let i = startIndex - 1; i >= 0; i--) {
                framesToDisplay.push(frames[i]);
            }
            for (let i = frames.length - 1; i >= endIndex; i--) {
                framesToDisplay.push(frames[i]);
            }
        } else {
            for (let i = startIndex + 1; i < frames.length; i++) {
                framesToDisplay.push(frames[i]);
            }
            for (let i = 0; i < endIndex; i++) {
                framesToDisplay.push(frames[i]);
            }
        }
    }

    isPlayingKeyframes = true;
    let i = 0;
    const playInterval = setInterval(() => {
        updateFrame(framesToDisplay[i].index);
        i++;
        if (i === framesToDisplay.length) {
            clearInterval(playInterval);
            currentFrameIndex = targetIndex;
            isPlayingKeyframes = false;
        }
    }, switchSpeed);
}

function getNextKeyframeIndex() {
    if (keyframeIndices.length === 0) return -1;

    const nextIndex = (currentKeyframeIndex + 1) % keyframeIndices.length;
    return keyframeIndices[nextIndex];
}

function getPrevKeyframeIndex() {
    if (keyframeIndices.length === 0) return -1;

    const prevIndex = (currentKeyframeIndex - 1 + keyframeIndices.length) % keyframeIndices.length;
    return keyframeIndices[prevIndex];
}

I already tried to add an index to each frame and tried to reverse the behavior but that didnt seem to work correctly

Lucia auth sveltekit problem with locals.user

I’m trying out Lucia with MongoDB, but there’s an issue. Whenever I sign in a user, I can see that the user is successfully inserted into the database. However, when I navigate to another route, I’m redirected back to the sign-in page, even though I just signed in. What could be causing this issue?

i tried debuggin some data, from hooks.server.ts but it still shows me null

how can i send the checked row to the first at datatables

This code actually works adding row, however when i checked the primary contact it didnt send to the first row instead it send to the last, kindly help me to fix this.

  //add row in contact
  $(document).ready(function () {
      var table = $('#lv_Lead_Contact_Information-datatable').DataTable({
          dom: "t"
      });

      //ensure the primary contract is only one
      $(document).on('change', '.primary-contact-checkbox', function () {
          if (this.checked) {
              // Uncheck all other checkboxes
              $('.primary-contact-checkbox').not(this).prop('checked', false);

              // Get the row of the checked checkbox
              var row = $(this).closest('tr');

              // Move the row to the top of the table
              row.fadeOut(function () {
                  table.row(row).remove().draw(false);
                  table.row.add(row[0]).draw(false);
                  row.fadeIn();
              });
          }
      });

      $(document).on('click', '#btnAddContact', function () {
          table.row.add([
              '<input type="checkbox" class="form-check-input primary-contact-checkbox" style="vertical-align: middle; margin-left: 21px;">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="checkbox" class="" style="vertical-align: middle; margin-left: 19px;">',
              '<input type="text" class="form-control form-control-borderless">'
          ]).draw();
      });
  });

How to Ignore Permissions Error with Apps Script on Google Sheets

I have an Apps Script that updates columns in a Google Sheet. It is only updating unprotected columns. At the end I do a sort on all columns (including some protected columns). Those without permissions get an error from google sheets.

I tried to put a try/catch statement on the sort but that did not work. Google sheets still gives the permissions error and the code stops.

Can I either put some form of a try/catch around the sort or can I somehow see if the user has permissions before the code executes?

Here is the code that gives the Google Sheets permission error:

var wb = SpreadsheetApp.openById(id)
var ss = wb.getSheetByName(sheetname)
var sortrange = ss.getRange('A5:AM')
sortrange.sort(1)

This is the try/catch I attempted:

var wb = SpreadsheetApp.openById(id)
var ss = wb.getSheetByName(sheetname)
var sortrange = ss.getRange('A5:AM')
try {
  sortrange.sort(1)
}
catch(Exception e) {
}

Trying to reduce Column A by 10% and then replace the old numbers in Column A with the new numbers

So I have almost zero knowledge of custom functions in Google Sheets. But I am trying to take the numbers in each cell in Column A, reduce it by 10%, then replace the old numbers with the new reduced number.
I.E. A1 is currently at 100, in a different cell call it B1 =(A1*(1-.1)), and then have the result in B1 replace the number in A1.

I’ve tried the built in functions =Value(Replace(A1:A40, 1, 3, K1:K40)) but it only replaces the column I enter the function in.
I need a custom function that will do this but I have no clue where to start. Any Advice would be appreciated.

npm error code EUSAGE when uploading react+vite project to GitHuB

Firstly here is the project repository where the error is occuring: https://github.com/tdM05/tdM05.github.io

I’m trying to deploy my website that I made with React+Vite to GitHub Pages and I keep getting a blank page (that isn’t error 404) and ever since I added the deploy.yml file which is in the .githubworkflows folder, I would get an error when pushing my commits to github. I added that file because that is what seemed like I should do from what I’ve read and I was getting a blank page before this.

Right now when I push to github, there is an error when github tries building it during the “install dependencies” phase. Here is the full error:

Run bahmutov/npm-install@v1
running npm-install GitHub Action
trying to restore cached NPM modules
cache key npm-linux-x64-f49928ddd0b76d21d99280ed45df323cea9587a11260ad9b9d67a7a11ca1895408c30700e1d2bbd849607dd72dd268408f86a41aba4ff79a9782a0ddb0a893c5
restore keys [
  'npm-linux-x64-f49928ddd0b76d21d99280ed45df323cea9587a11260ad9b9d67a7a11ca1895408c30700e1d2bbd849607dd72dd268408f86a41aba4ff79a9782a0ddb0a893c5',
  [length]: 1
]
input paths [ '/home/runner/.npm', [length]: 1 ]
npm cache miss
installing NPM dependencies
npm at "/opt/hostedtoolcache/node/18.20.4/x64/bin/npm"
/opt/hostedtoolcache/node/18.20.4/x64/bin/npm ci
npm error code EUSAGE
npm error
npm error `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm error
npm error Missing: @types/[email protected] from lock file
npm error
npm error Clean install a project
npm error
npm error Usage:
npm error npm ci
npm error
npm error Options:
npm error [--install-strategy <hoisted|nested|shallow|linked>] [--legacy-bundling]
npm error [--global-style] [--omit <dev|optional|peer> [--omit <dev|optional|peer> ...]]
npm error [--include <prod|dev|optional|peer> [--include <prod|dev|optional|peer> ...]]
npm error [--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit]
npm error [--no-bin-links] [--no-fund] [--dry-run]
npm error [-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
npm error [-ws|--workspaces] [--include-workspace-root] [--install-links]
npm error
npm error aliases: clean-install, ic, install-clean, isntall-clean
npm error
npm error Run "npm help ci" for more info

npm error A complete log of this run can be found in: /home/runner/.npm/_logs/2024-08-22T01_20_31_209Z-debug-0.log
Error: The process '/opt/hostedtoolcache/node/18.20.4/x64/bin/npm' failed with exit code 1
    at ExecState._setResult (/home/runner/work/_actions/bahmutov/npm-install/v1/dist/index.js:6056:25)
    at ExecState.CheckComplete (/home/runner/work/_actions/bahmutov/npm-install/v1/dist/index.js:6039:18)
    at ChildProcess.<anonymous> (/home/runner/work/_actions/bahmutov/npm-install/v1/dist/index.js:5933:27)
    at ChildProcess.emit (node:events:519:28)
    at maybeClose (node:internal/child_process:1105:16)
    at ChildProcess._handle.onexit (node:internal/child_process:305:5)
Error: The process '/opt/hostedtoolcache/node/18.20.4/x64/bin/npm' failed with exit code 1

These are the things that I’ve done so far:

  • changed vite.config.js to add the property base: "/" because my github repository is called tdM05.github.io. Nothing seemed to happen (which is expected because “/” seems to be the default value).
  • added this "homepage": "http://tdM05.github.io" to my package.json file. Nothing seemed to change.
  • Changed "private": true, to "private": false, in my package.json file. Nothing seemed to change.
  • Ran npm install again. Nothing changed.

Does anyone know what is going wrong? Any help would be greatly appreciated.

Combine heat map data and different markers data in one Google Map

Can you combine heat map & markers on one Google Map? The heat map will show crime incidents while the markers need to show neighborhood watch members.

So far I can get either or of them to show, I have an idea that I’m not grasping the concept of Google Map layers correctly.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
  </head>

  <body>

    <div id="map"></div>
    <script>

var map, heatmap;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 16,
    center: { lat: -28.504330, lng: 27.931830 },
    mapTypeId: google.maps.MapTypeId.SATELLITE
  });

  heatmap = new google.maps.visualization.HeatmapLayer({
    data: getPoints(),
    map: map
  });

  heatmap.set('radius', 15);

// Create a pin element.
const pin = new PinElement({
    scale: 1.5,
});
// Create a marker and apply the element.
const marker = new AdvancedMarkerElement({
    map,
    position: { lat: -28.506650, lng: 27.941490 },

});


}


function getPoints() {
  return [
    new google.maps.LatLng(-28.504440, 27.932060),
    new google.maps.LatLng(-28.504330, 27.931829)
  ];
}

    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key={an API key}&signed_in=true&libraries=visualization,marker&callback=initMap">
    </script>
  </body>
</html>

How to Trigger 1-Click Facebook OAuth Consent Dialog Instead of Multi-Step Flow

I’m attempting to use Meta’s OAuth login for a project, however, the dialog is always a complex multi-step process. Several other sites have a simple, 1-click dialog. I noticed that whether I use the SDK or url, it ends up being the same result. Additionally, the url for the 1-click dialog is much longer and always starts with “https://www.facebook.com/privacy/consent/gdp/?params%5Bapp_id%”.

1-click Dialog
Multi-step Dialog

Ss there any way to get the simpler login dialog on my end, or is it up to Meta?

I tried using both the SDK and a manual login with differing login settings. I also tried adding and removing scopes as well as all the possible auth_types to no avail. I also am testing in live mode/production.

I need help sprite animation with CSS and JS

I made this simple project that allows a 4-image sprite to move in one direction, but I would like to know how I can do this so that whenever the D key (key that moves the character) is not being pressed, the AnimationIndex is the same to 0, giving the impression that the character has stopped.

        $(document).ready(function () {
            var V = 40;
            var boneco = $('.boneco');
            var animacoes = ['direita', 'direita2', 'direita3', 'direita4']; // 4 pois o sprite de andar para a direita contém apenas 4 imagens
            var animacaoIndex = 1;
            var teclaDisponivel = true;

            function moverBonecoDireita() {
                var andou = parseInt(boneco.css('margin-left')) || 0; // lembrar: tudo que vem do css vem como string, usar parseInt para converter
                var larguraTela = $(window).width(); // tam tela
                var larguraBoneco = boneco.width(); // tam boneco

                if (andou + V + larguraBoneco <= larguraTela) {
                    boneco.removeClass(animacoes[animacaoIndex]);
                    animacaoIndex = (animacaoIndex + 1) % animacoes.length;
                    boneco.addClass(animacoes[animacaoIndex]);
                    boneco.css('margin-left', (andou + V) + 'px');
                }
            }

            $(document).on('keypress', function (evento) {
                var tecla = evento.keyCode;
                if (tecla == 100 && teclaDisponivel) { // tecla 'd'
                    teclaDisponivel = false;
                    moverBonecoDireita();
                    setTimeout(function () {
                        teclaDisponivel = true;
                    }, 110);
                } else if (tecla == 97) { // tecla 'a'
                    boneco.removeClass(animacoes.join(' '));
                    boneco.css('margin-left', '0px');
                    animacaoIndex = 1;
                }
            });
        });

I tried to create a command block so that, when pressing the D key, animationindex would be equal to 0, but I failed

Why the input eventlistener with change is not getting the value

I have these three inputs of type number where you can only add one number and you can replace it by pressing any other number between 0 and 9. I have 2 eventlisteners on these inputs the first is to be able to change the value of the inputs by pressing a number between 0 and 9 (by using ‘keyup’). The second eventlistener is there for detecting input and then calculating the total of the three input, when the correct total is calculated an alert is thrown. What I have noticed is if I want a total of 27 for example I need to add 9 + 9 + 9 in inputs. However if I add 9 + 8 + 9 but then without deleting the 8 and just replacing it by pressing 9 I don’t get the alert. To get the total the better seems to do it within the event listener with ‘keyup’. So why is that? When pressing the 9 button it is still an input event as well?

const element1 = document.querySelector('.element1')
let total = 0
let desiredTotal = 27

    let allInputs = Array.from(element1.getElementsByTagName('input'))
    allInputs.forEach((input)=>{
        input.style.border = '2px solid blue'
        input.addEventListener('keyup', (e)=>{
            if(e.target.value.length === 1 && parseFloat(e.key) >= 0 && parseFloat(e.key) <=9){
                    e.target.value = e.key
            }
        })
    })


    allInputs.forEach((input)=>{
        let value
        input.addEventListener('input', (e)=>{
            let value = parseFloat(input.value)
            total += value
            console.log(total)
            if(total === 27) alert('you won!')
        })

    })
input{
    width: 2ch;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type=number] {
  appearance: textfield;
}
<body>
    <div class="element1">
        <input type="number" name="" id="input1" onKeyPress="if(this.value.length===1 || event.key == 'e') {return false}">
        <input type="number" name="" id="input2" onKeyPress="if(this.value.length===1 || event.key == 'e') {return false}">
        <input type="number" name="" id="input3"onKeyPress="if(this.value.length===1 || event.key == 'e') {return false}">
    </div>
    <p>Try to obtain a total of 27</p>
    <p>Try to place 9 9 and then 9 you get the alert</p>
    <p>Try to place 9 6 and then 9 but then change(without deleting) but pressing on the 6 containing input the number 9 you won't get the alert</p>
</body>

useState hook not updating ReactNode [duplicate]

I’m new to React and don’t exactly understand the useState hook. Why does the “TaSkrol” element not rerender when allTasks is updated?

(taskroll is just a scrollview that contains alltasks)

export default function App() {
  tests()
  const [currentTab,setTab] = useState('tab1')
  const [allTasks,setalltasks] = useState<ReactNode[]>(()=>TaskListFromTab(currentTab))
  function addtask(task:Record<string,any>){
    let t =  loadItem(createTask(currentTab,task))
    let a = allTasks
    a.push(<Task key ={t.adress} data = {t}/>)
    setalltasks(a)
    console.log(allTasks)
  }
  return (
    <View style={styles.container}>
      {Tabs(currentTab)}
      <View
        id="notes+createnote"
        style={{
          marginBottom: 0,
          paddingBottom: 0,
          height: 'auto',
          width: '100%',
          borderTopLeftRadius: 20,
          borderTopRightRadius: 20,
          backgroundColor: colors.lowBlue,
          flex: 1
        }}
      >
        <TaSkroll tasks={allTasks} />
        <View id="padding" style={{ flex: 1 }}></View>
        {newTask(currentTab,addtask)}
      </View>
      <StatusBar hidden={true} style="auto" />
    </View>
  );
}

newtask is a button with alltasks as the onpress.i tried using a useeffect with current tab and alltasks as the dependencies but that didnt work

Socket.io events in React.js and Node.js not being triggered

I’m building a chat application in React js and Node js. The events that I have written in React.js and Node.js do not seem to be triggered. I can login and see data in both the browser and the console, but as soon as I installed Socket.IO for the client and server, not only did I get issues from Socket.IO on the client side, none of the events are being triggered.

socketConnect.js in the client side

import { useEffect } from "react";
import socketIOClient from "socket.io-client"

function useSocket (user, dispatch) {

    useEffect(() => {

        const socket = socketIOClient.connect("http://127.0.0.1:3000")

        socket.emit("join", user)

        socket.on("typing", (user) => {
            console.log("Event", user)
        })

        socket.on("friends", (friends) => {
            console.log("Friends", friends)
        })

        socket.on("online", (user) => {
            console.log("Online", user)
        })

        socket.on("offline", (user) => {
            console.log("Offline", user)
        })
    }, [dispatch])

}

export default useSocket

/socket/index.js in the server side

const socketIo = require("socket.io");
const { sequelize } = require("../models");

const users = new Map();
const userSockets = new Map();
const SocketServer = (server) => {

    const io = socketIo(server)
    io.on("connection", (socket) => {
        socket.on("join", async (user) => {
            let sockets = [];
            if (user.has(user.id)){
                const existingUser = users.get(user.id)
                existingUser.sockets = [...existingUser.sockets, ... [socket.id]]
                users.set(user.id, existingUser);
                sockets = [...existingUser.sockets, ... [socket.id]]
                userSockets.set(socket.id, user.id)
            } else {
                users.set(user.id, {id: user.id, sockets: [socket.id]})
                sockets.push(socket.id);
                userSockets.set(socket.id, user.id)
            }
            const onlineFriends = []; 

            const chatters = getChatters(user.id) 

            console.log(chatters);

            for (let i = 0; i < chatters.length; i++){
                if (users.has(chatters[i])){
                    const chatter = users.get(chatters[i])
                    chatter.sockets.forEach(socket => {
                        
                        try {
                            io.to(socket).emit("online",user);
                        } catch (error) {
                            
                        }

                    })
                    onlineFriends.push(chatter.id)
                }
            }
            sockets.forEach(socket => {
                try {
                    io.to(socket).emit("friends", onlineFriends)

                } catch (error) {
                    
                }
            })

            console.log("New User Joined: ", user.firstName);

            io.to(socket.id).emit("typing", "User typing...")

        })

        socket.on("disconnect", async () => {

            if (userSockets.has(socket.id)){

                const user = users.get(userSockets.get(socket.id))

                if (user.sockets.length > 1) {

                    user.sockets = user.sockets.filter(sock => {

                        if (sock !== socket.id) return true

                        userSockets.delete(sock)
                        return false
                    })

                    users.set(user.id, user)
                } else {
                    
                    const chatters = await getChatters(user.id)

                    for (let i = 0; i < chatters.length; i++){
                        if (users.has(chatters[i])){
                            users.get(chatters[i]).sockets.forEach(socket => {
                                
                                try {
                                    io.to(socket).emit("offline",user);
                                } catch (error) {
                                    
                                }
        
                            })
                        }
                    }
                    userSockets.delete(socket.id);  
                    users.delete(user.id)
                }
            }
        });
    })
}

const getChatters = async (userId) => {

    try {

        const [results, metadata] = await sequelize.query(`
        select "cu"."userId" from "ChatUsers" as cu
        inner join (
            select "c"."id" from "Chats" as c
            where exists (
                select "u"."id" from "Users" as u
                inner join "ChatUsers" on u.id = "ChatUsers"."userId"
                where u.id = ${parseInt(userId)} and c.id = "ChatUsers"."chatId"
            )
        ) as cjoin on cjoin.id = "cu"."chatId"
        where "cu"."userId" != ${parseInt(userId)}
    `)

        return results.length > 0 ? results.map(el => el.userId) : []

    } catch (e) {
        console.log(e);
        return []
    }
}

module.exports = SocketServer

root index.js in the server side

const express = require("express");
const config = require('./config/app')
const router = require('./router');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const http = require("http");
const socketIo = require("socket.io")

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.use(router);
app.use(express.static(__dirname + "/public"));
app.use(express.static(__dirname + "/uploads"));

const port = config.appPort;

const server = http.createServer(app);
const SocketServer = require("./socket")
const io = socketIo(server);

SocketServer(server);

io.on("connection", (socket) => {
    console.log("New client connected: ", socket.id);

    socket.on("join", (user) => {
        console.log("New user joined: ", user);
        io.to(socket.id).emit("typing", "User typing...");
    });

    socket.on("disconnect", () => {
        console.log("Client disconnected: ", socket.id);
    });
});



server.listen(port, () => {
    console.log(`Server is running on port ${port}`)    
});


Chat.js which renders the components

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import useSocket from './hooks/socketConnect'
import Navbar from './components/Navbar/Navbar'
import { fetchChats } from '../../store/actions/chat'
import FriendList from './components/FriendList/FriendList'
import Messenger from './components/Messenger/Messenger'
import './Chat.scss'

const Chat = () => {

    const dispatch = useDispatch()
    const user = useSelector(state => state.authReducer.user)

    useSocket(user, dispatch)

    useEffect(() => {
        dispatch(fetchChats()).then(res => console.log(res)).catch(err => console.log(err))
    }, [dispatch])

    return (
        <div id='chat-container'>
            <Navbar />
            <div id='chat-wrap'>
                <FriendList />
                <Messenger />
            </div>
        </div>
    );
}

export default Chat```








I have multiple users in the database. When a user logs in and is online, another user from the database, if logged in, will be notified from the console, but none of the events are being triggered.

Swiper JS SlidesPerView bug with custom width on active slide

I have been trying to solve this for a long time. I want to expand the width of the active slide when swiping in Swiper JS without using centeredSlides. But there seems to be a bug that I cannot solve.
The slides should be aligned to the left and when I swipe I can’t see the last two slides.

Here is the bug on codepen.

https://codepen.io/Xteripus/pen/BagrOyE

 var projectsSwiper = new Swiper(".projects-swiper", {
      slidesPerView: "auto",
      spaceBetween: 50,
      navigation: {
        prevEl: ".js-projects-nav .btn-prev",
        nextEl: ".js-projects-nav .btn-next",
      },
    });

Thanks.