Implementation of Redux Persist with Redux Toolkit. After implementation, can’t see todos

Today i tried to implement redux persist to save todos in the local storage.
I have made everything right using documentation, but the problem now is that i have todos in the local storage, but can’t see todos in the app.
Before implementation, everything works fine. Must understand this part of using locaStorage with redux toolkit/redux-persist.

I just leave here the github repo: https://github.com/DanielCapcelea/todo-with-motion

If someone can show where i have made an error. Please or pull request or answer here.

Thx a lot!

store.js

import {combineReducers, configureStore} from "@reduxjs/toolkit";
import {
    persistStore,
    persistReducer,
    FLUSH,
    REHYDRATE,
    PAUSE,
    PERSIST,
    PURGE,
    REGISTER,
} from 'redux-persist';
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
import todoReducer from './todoSlice';


const rootReducer = combineReducers({
    todoReducer,
});

const persistConfig = {
    key: 'root',
    storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer)


const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
            },
        }),
});

export const persistor = persistStore(store);
export default store;

todoSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = [];

const todoSlice = createSlice({
    name: "todos",
    initialState,
    reducers: {
        //Adding todos
        addTodos: (state, action) => {
            state.push(action.payload);
            return state;
        },
        //remove todos
        removeTodos: (state, action) => {
            return state.filter((item) => item.id !== action.payload);
        },
        //update todos
        updateTodos: (state, action) => {
            return state.map((todo) => {
                if (todo.id === action.payload.id) {
                    return {
                        ...todo,
                        item: action.payload.item,
                    };
                }
                return todo;
            });
        },
        //completed
        completeTodos: (state, action) => {
            return state.map((todo) => {
                if (todo.id === action.payload) {
                    return {
                        ...todo,
                        completed: !todo.completed,
                    };
                }
                return todo;
            });
        },
    },
});

export const {
    addTodos,
    removeTodos,
    updateTodos,
    completeTodos,
} = todoSlice.actions;

export default todoSlice.reducer;

displayTodos.js

import React, {useState} from "react";
import {connect} from "react-redux";
import {
    completeTodos,
    removeTodos,
    updateTodos,
} from "../redux/todoSlice";
import TodoItem from "./TodoItem";
import {AnimatePresence, motion} from "framer-motion";

const mapStateToProps = (state) => {
    return {
        todos: state,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        removeTodo: (id) => dispatch(removeTodos(id)),
        updateTodo: (obj) => dispatch(updateTodos(obj)),
        completeTodo: (id) => dispatch(completeTodos(id)),
    };
};

const DisplayTodos = (props) => {
    const [sort, setSort] = useState("active");
    return (
        <div className="displaytodos">
            <div className="buttons">
                <motion.button
                    whileHover={{scale: 1.1}}
                    whileTap={{scale: 0.9}}
                    onClick={() => setSort("active")}
                >
                    Active
                </motion.button>
                <motion.button
                    whileHover={{scale: 1.1}}
                    whileTap={{scale: 0.9}}
                    onClick={() => setSort("completed")}
                >
                    Completed
                </motion.button>
                <motion.button
                    whileHover={{scale: 1.1}}
                    whileTap={{scale: 0.9}}
                    onClick={() => setSort("all")}
                >
                    All
                </motion.button>
            </div>
            <ul>
                <AnimatePresence>
                    {props.todos.length > 0 && sort === "active"
                        ? props.todos.map((item) => {
                            return (
                                item.completed === false && (
                                    <TodoItem
                                        key={item.id}
                                        item={item}
                                        removeTodo={props.removeTodo}
                                        updateTodo={props.updateTodo}
                                        completeTodo={props.completeTodo}
                                    />
                                )
                            );
                        })
                        : null}
                    {/* for completed items */}
                    {props.todos.length > 0 && sort === "completed"
                        ? props.todos.map((item) => {
                            return (
                                item.completed === true && (
                                    <TodoItem
                                        key={item.id}
                                        item={item}
                                        removeTodo={props.removeTodo}
                                        updateTodo={props.updateTodo}
                                        completeTodo={props.completeTodo}
                                    />
                                )
                            );
                        })
                        : null}
                    {/* for all items */}
                    {props.todos.length > 0 && sort === "all"
                        ? props.todos.map((item) => {
                            return (
                                <TodoItem
                                    key={item.id}
                                    item={item}
                                    removeTodo={props.removeTodo}
                                    updateTodo={props.updateTodo}
                                    completeTodo={props.completeTodo}
                                />
                            );
                        })
                        : null}
                </AnimatePresence>
            </ul>
        </div>
    );
};

export default connect(mapStateToProps, mapDispatchToProps)(DisplayTodos);

Vue.js dynamic image src with require is not defined error

I’m trying to bind image src dynamically to a url in a v-for loop as below :

<script>
export default {    
    name: 'Home',
    data() {
        return {
            games: [
                {"gameId": 1365, "gameLabel": "ssbu"},
                {"gameId": 1366, "gameLabel": "ggs"},
                {"gameId": 1367, "gameLabel": "sf5"},
            ]
        }
    }
};
</script>

<template>
  <div v-for="game in games"">
    <img :src="`../assets/cards/${game.gameLabel}.jpg`" :alt="game.gameLabel">
  </div>
</template>

But I had the error GET http://localhost:3000/assets/cards/ssbu.jpg 404 (Not Found) although it works fine when I do this : <img src="../assets/cards/ssbu.jpg" :alt="game.gameLabel">.

So i tried using require function as people mentionned in other posts with something like this : <img :src="require(`../assets/cards/${game.gameLabel}.jpg`)" :alt="game.gameLabel"> but there I faced the fatal error ReferenceError: require is not defined.

SO I’m stuck at this point and I need your help in order to resolve this problem.

Thanks in advance.

Remove null attributes from an Object in Typescript

As reference Remove blank attributes from an Object in Javascript, how to make it Typescript compatible?

JS function (nested objects | ES10):

function removeEmpty(obj) {
  return Object.fromEntries(
    Object.entries(obj)
      .filter(([_, v]) => v != null)
      .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
  );
}

I’ve tried with Exclude<T, null> but it doesn’t works with nested objects and I think it’s not the correct utility to use.

Note that the returned type should remove null type(s) but keeps undefined.

Example/Expected behaviour:

type TestType = {
  a?: {
    b?: {
      c: string;
    } | null;
    z?: {
      x: string;
    };
  } | null;
};

const testObj: TestType = {
  a: {
    b: null,
    z: { x: 'Hi' }
  }
};

const resultObj = removeEmpty(testObj);

Where resultObj type is similar to:

type ResultTypeExample = {
  a?: {
    b?: {
      c: string;
    };
    z?: {
      x: string;
    };
  };
};

How can i align a bootstrap table?

I am trying to align my bootstrap table but I cant. I want it like as bootstrap class ‘d-flex justify-content-between’. if i have 3 items in my table ,I want 1st one in the left 2nd one middle and last one in the right side. but here it takes places by its own way.

firebase signOut() method doesn’t sign out

I use firebase v9 and created a react hook for convenient verification of user authorization.
After authorization, I can’t log out on the page as if the signOut() method just doesn’t work

firebase.ts

import { initializeApp } from "firebase/app";
import {getAuth} from "firebase/auth";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID
};

const app = initializeApp(firebaseConfig);

export const auth = getAuth();

useAuth.ts

import {useEffect, useState} from "react";

import {onAuthStateChanged, User} from "firebase/auth";
import {auth} from "../firebase";

export const useAuth = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const subscriber = onAuthStateChanged(auth, (userInfo) => {
      if (userInfo) {
        setIsLoggedIn(true);
        setUser(userInfo);
      } else {
        setIsLoggedIn(false);
        setUser(null);
      }
    });
    return () => {
      subscriber();
    }
  }, []);

  return {
    user,
    isLoggedIn,
  };
}

HomePage.ts

import React from 'react';

import {signOut} from "firebase/auth";
import {Navigate} from "react-router-dom";
import {useAuth} from "../hooks/useAuth";
import {auth} from "../firebase";

const HomePage = () => {
  const { isLoggedIn } = useAuth();

  const handleLogOut = () => {
    signOut(auth)
      .then(r => console.log(r)) // undefined
      .catch();
  };

  return (
    {isLoggedIn} ?
      <div>
        <h1>Welcome</h1>
        <button onClick={handleLogOut}>
          Log Out
        </button>
      </div>
      : <Navigate to='/login' />
  );
};

export default HomePage;

At the same time, when I refresh the page, the session is not reset and I remain on the home page. What am I doing wrong?

How to get offset position of HTML elements in react when using react-scroll-motion

I am trying to get offsetTop positions of all of sections in DOM. I need it so that, I can change URL in browser when I scroll to a specific section. I can get the offsetTop position when component renders. But, when I use my components inside of react-scroll-motion, it gives me 0 as offsetTop position for all components. How can I get offsetTop position while still using react-scroll-motion library?

Below is the code with using react-scroll-motion

const Home: NextPage = () => {

  const [firstRender, setFirstRender] = useState(0);
  const [sections, setSections] = useState(null);
  const [isBrowser, setIsBrowser] = useState(false);

  useEffect(() => {
    setIsBrowser(typeof window !== undefined ? true : false);
    setFirstRender(1);
  }, []);

  useEffect(() => {
    const sectionsList = document.querySelectorAll('section');
    const sectionsData: any = {};
    for (let i = 0; i < sectionsList.length; i++) {
      console.log(sectionsList[i].offsetTop); // gives 0 when renders
      sectionsData[`${sectionsList[i].id}`] = {
        'offsetTop': sectionsList[i].offsetTop,
        'id': sectionsList[i].id
      }
    }
    setSections(sectionsData);
  }, [firstRender]);

  const contentItems = [<Hero/>, <About/>, <RoadMap/>,  <Team/>];

  const content = linksData.map((item, index) => {
    return (
      <section id={item.text} key={index}>
        <ScrollPage page={item.page}>
          <Animator animation={batch(item.sticky, item.fade, item.move)}>
            {contentItems[index]}
          </Animator>
        </ScrollPage>
      </section>
    )
  })

  return (
    <>
      { 
        isBrowser && 
        (
          <Container>
            <Navbar/>
            <Main>
              <MovingParticles/>
              <ScrollContainer>
                {content}
              </ScrollContainer>
            </Main>
          </Container>
        )
      }
    </>

  )
}

export default Home;

Below is code that gives correct offsetTop position when I do not wrap my components inside react-scroll-motion

const Home: NextPage = () => {

  const [firstRender, setFirstRender] = useState(0);
  const [sections, setSections] = useState(null);
  const [isBrowser, setIsBrowser] = useState(false);

  useEffect(() => {
    setIsBrowser(typeof window !== undefined ? true : false);
    setFirstRender(1);
  }, []);

  useEffect(() => {
    const sectionsList = document.querySelectorAll('section');
    const sectionsData: any = {};
    for (let i = 0; i < sectionsList.length; i++) {
      console.log(sectionsList[i].scrollHeight);
      sectionsData[`${sectionsList[i].id}`] = {
        'offsetTop': sectionsList[i].offsetTop,
        'id': sectionsList[i].id
      }
    }
    setSections(sectionsData);
  }, [firstRender]);

  const contentItems = [<Hero/>, <About/>, <RoadMap/>,  <Team/>];

  const content = linksData.map((item, index) => {
    return (
      <section id={item.text} key={index}>
            {contentItems[index]}
      </section>
    )
  })

  return (
    <>
      { 
        isBrowser && 
        (
          <Container>
            <Navbar/>
            <Main>
              <MovingParticles/>
                {content}
            </Main>
          </Container>
        )
      }
    </>

  )
}

export default Home;

How to get offsetTop position with using react-scroll-motion?

P2P comunication between Unity and browser

I am looking for a way to comunicate between my unity app and a browser with a socketio server and a stun server.

I am able to send messages between both of them and to establish a p2p connection between 2 browser pages using the unity render streaming package, but I need to establish a p2p connection between a browser and my unity app.
I have been through the internet for the past weeks, and most of the solution I found use websocket.

I don’t get why, but my server uses socket.io and when looking at the browser network panel, I see the communication is on
ws://localhost:81/socket.io/?EIO=3&transport=websocket&sid=MYSIDISHERE and I am sure I got rid of the websocket part of my app, only using socketio now (i know there is a link between those, from what I understood, socketio uses the websocket protocol, is that right ?). Other solutions I found seem deprecated.

To summarize, i want to establish a P2P connection between some js code and unity (c#) through socketio.

Anyone has an idea about this, or some documentation ?

Javascript – ‘this’ is undefined within a Class’s function

I have a simple Class for a ProgressBar —

var progressBar;

class ProgressBar {
    constructor( ) {
        this.loading = { };
        for( var s in Sprites ) {
            this.loading[s] = { count: 0, max: 0 };
        }
        
        this.count      = 0;
        this.progress   = 0;
        this.max        = 0;
        this.density    = 1;
        this.percentage = '0%';
        
        console.log( this );
    }
    update( ) {
        console.log( this ); // trying to debug 'this', which returns Undefined
        
        this.count * this.density < this.progress && this.progress++;       
        this.percentage = Math.floor( this.progress / this.max * 100 ) / this.density + '%';
        
        $('#screen-loading-container-bar-inner').css( { 'width': this.percentage } );
        $('#screen-loading-container-bar-text').text( this.percentage );
        
        this.progress != this.max * this.density ? requestAnimationFrame( this.update ) : this.complete( );
    }
}

progressBar = new ProgressBar( );

defineResources( );

progressBar.update( ); // this gives me error - "Uncaught TypeError: Cannot read properties of undefined (reading 'count')"

function defineResources( ) {
    new Sprite( 'img/sprites/S_Ship_Hull.png', 'ship', 'hull' );
    
    if( progressBar.max == 0 ) {
        console.log( '%c No resources detected! ', 'font-weight: bold; font-size: 16px;color: red; text-shadow: 1px 1px 0 rgba(0,0,0,0.3);' );
        progressBar.complete( );
    }
    else {
        console.log( '%c' + progressBar.max + ' resources detected', 'font-weight: bold; font-size: 16px;color: green; text-shadow: 1px 1px 0 rgba(0,0,0,0.3);' );
    }
}

console.log( this ) in the constructor( ) function returns value.

console.log( this ) in the update( ) function returns undefined. What’s the issue?

JavaScript How to execute firstPromise before secondPromise

This might seem a silly question, but I am a newbie in this topic. In the script below i have two promises. By now “secondPromise” executing first, and then executing “firstPromise”. Cuz in the “secondPromise” i set less time. But how to execute “firstPromise” first, after finished that, start executing the “secondPromise”?
How to rewrite the script below

(async function()
{
//var final = new Array();
var final;
const firstPromise = new Promise(
function(resolve)
{
    let result = 2 + 2;
    resolve(result);
    setTimeout(() => console.log("please show me first"), 2000);
});
const secondPromise = new Promise(
function(resolve)
{
    let result2 = 0;
    resolve(result2 + 1);
    setTimeout(() => console.log("please show me second"), 1000);
});
var myP = Promise.all([firstPromise, secondPromise]).then((values) => {
    return values[0]+values[1];
  });
return myP;
})();

(async function()
{
//var final = new Array();
var final;
const firstPromise = new Promise(
function(resolve)
{
    let result = 2 + 2;
    resolve(result);
    setTimeout(() => console.log("please show me first"), 2000);
});

const secondPromise = new Promise(
function(resolve)
{
    let result2 = 0;
    resolve(result2 + 1);
    setTimeout(() => console.log("please show me second"), 1000);
});

var myP = Promise.all([firstPromise, secondPromise]).then((values) => {
    return values[0]+values[1];
  });
return myP;
})();

how to update a cell, row by row datatable

I have the following problem, I have these inputs, the two main CODE AND DESCRIPTION, it paints them automatically, the other 3 I have to fill them. When adding an existing record, what it does is add the QUANTITY value with the one already registered. But the problem is that in the 2nd record the sum is made for all the fields of all the rows, I would like it to do the sum individually row by row.

enter image description here

"columns": [ //code where the input is located inside the table
            { "data": "ProductoFila" },
            { "data": "ProductoCodigo" },
            { "data": "ProductoNombre" },
            { "data": "ProductoCostoActual"
                , render: function (data) {
                    return ' <input type="text" id="tableCostoActual" style="font-size: 12px;" class="form-control text-center floatNumberField" value="' + parseFloat(data).toFixed(6) + '">';
            }
            },
            { "data": "ProductoCantidad"
                , render: function (data, type, row) {
                    return '<input type="text" id="tableCantidad" style="font-size: 12px;"  class=" form-control full-width text-lg-center" value="' + parseFloat(data).toFixed(0) + '" >';
                }
            },
            { "data": "Descuento"
                , render: function (data, type, row) {
                    return ' <input type="text" id="tableDescuento" style="font-size: 12px;" class="form-control text-center floatNumberField" value="' + parseFloat(data).toFixed(6) + '">';
                }
            },
            { "data": "ProductoTotal" },
            {
                //pestaña no agregada en DB
                "defaultContent": '<button type="button" class="btn btn-danger btn-sm ms-2 btn-eliminar"> <i class="fas fa-trash"></i> </button>', //ms-2: modificar las distancia de separacion del icono
                "orderable": false,
                "searchable": false, // ESTO SIGNFICA QUE AL MOMENTO DE BUSCAR UN CONTACTO, NO MUESTRE ESTE COLUMNA CON LOS DOS BOTONES
                "width": "20px" //modificar ancho de la columna
            }
        ],




        //Find if a product exists  
        var productoNuevo = 0;
        var row = tabladata.row(4).node();
        var text = parseInt($("#txtCantidad").val()) + parseInt($("#tableCantidad").val());
      
  
        tabladata
            .column(1)
            .data()
            .each(function (value, index) {
                if (value == $("#txtCodigo").val()) {
                    productoNuevo = 1;
                    /*tabladata.cell(row, 4).data(text).draw();*/
                    tabladata.column(4).nodes().each(function (node, index, dt) {
                        tabladata.cell(node).data(text);
                    });
                  
                    toastr["warning"]("Producto ya existe")
                }
            });

How to swap keys and values in an object? JS

Please tell me how to get such an array where id : newExcluded(key), and excluded :(newExcluded value )

  const newExcluded = {1:true,6:false,3:false,4:true,7:true}
    
     coonst fetchExcluded = [
        {"id": 1,"excluded": true},
        {"id": 6, "excluded": false},
        {"id": 3, "excluded": false},
        {"id": 4, "excluded": true},
        {"id": 7, "excluded": true},
       ]

It’s this statement a bad practice?

I have been looking for information about the following line of code to know if it is a bad practice or it is good.

1 – I create a constant, initializing it with the value returned by querySelector

const el= document.querySelector('.some-el');

2 – use the value of the constant.
Here, I do not check if el exist inside in if statement I just :

el && el.click()

That’s ok?

Playwright ” no tests found.” after specifying testMatch in config file

So I ran the command npx playwright test on the CLI and got ” no tests found” in return.
Am I doing something wrong here?

playwright.config.js

/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
    use : {
        testDir: './tests',
        headless: false,
        channel: "chrome",
        screenshot: "only-on-failure",
        video: "retry-with-video"
    },
    testMatch: /testCopy.js/,
    retries: 2,
    reporter: [["dot"], ["json", {outputFile: "test-result.json"}]]
};
module.exports = config;

testCopy.js

const { test, expect } = require('@playwright/test');



test('Navigate to login page', async( { page } ) => {
    page = await browser.new
    await page.goto("http://localhost:3000/trader-desktop/login");
    const title = page.title();
    expect(title).toBe('Trader App');
    await page.pause();
});


test('Token Authentication', async( {page, localStorage} ) => {
    const fs = require('fs');
    const localStorage = fs.readFileSync('../localStorage.json', 'utf8');
    const deserializedStorage = JSON.parse(localStorage);
    await page.evaluate(deserializedStorage => {
        for (const key in deserializedStorage) {
            if (key === "realms") {
                localStorage.setItem(key, JSON.stringify(deserializedStorage[key]));
            }
            else {
                localStorage.setItem(key, deserializedStorage[key]);
            }
        }
    }, deserializedStorage);
});
      
test('Navigate to Surya Traders transcations page', async( { page}) => {

    await page.goto("http://localhost:3000/trader-desktop/account-selection")

    await page.click("text = Suriya traders");

    await page.click("text = Transactions");

    await page.click("text = Paid");
});

test('Download Excel', async( {page} ) => {
    const [ download ] = await Promise.all([
        page.waitForEvent('download'),
        page.locator('text = Download Excel').click(),
      ]);
    await download.saveAs('paidSheet.xlsx');
    await download.delete()
});

test('Close browser', async( {page} ) => {
    await page.pause();
    await browser.close();
});

Do I need to import the config file in my testCopy.js or is there something I missed out on or doing something wrong?

Thanks in advance 🙂

Why this code for reversing a string in Javascript is not working? [closed]

Code:
I am following the approach in which I have taken 2 variables i,j and i am running a while loop till i<=j.

const str = "JavaScript is awesome"

function reverseAString(str) {
     // write your solution here
     let i=0;
     let j=str.size-1;
     while(i<=j){
         let temp=str[i];
         str[i]=str[j];
         str[j]=temp;
         i++;
         j--;
     }

   return str.split('').reverse().join('');
}

console.log(reverseAString(str));

Creating custom scrollbar with JS

I’m trying to create a scrollbar using JS. I know this has been done before, but I wanted to try to make one myself.

I’m having a hard time setting the “scroll position” of the scroll thumb, it seems to drag behind and act very strangely and I guess I’m just too stupid to think through the problem myself.

Any help would be great 🙂 I highligted the problem with a comment, so you dont need to look through all of the unnecessary stuff

<div id = "wrapper">
        
        <div id="content">
            <ul>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
                <li>
                    helloworld
                </li>
            </ul>
        </div>
    </div>
Object.prototype.SetStyleObject = function(styleObject) {
  for (var key in styleObject) {
    this.style[key] = styleObject[key];
  }
};

function clamp(value, min, max) {
  return value > max ? max : value < min ? min : value;
}
const styles = {
  scrollbar: {
    right: '0px',
    position: 'absolute',
    width: '20px',
    height: '100%',
    background: 'red'
  },
  scrolltrack: {
    position: 'relative',
    height: '100%',
    width: '100%'
  },
  scrollthumb: {
    position: 'absolute',
    width: '100%',
    height: '20px',
    borderRadius: '10px',
    top: '0px',
    backgroundColor: 'green'
  }
}

function SetScrollbar(wrapper, content) {
  let scrollbar = null,
    scrolltrack = null,
    scrollthumb = null,
    MousePos = null,
    GetMousePos = null;
  thumbHeight = 0;

  function CreateScrollElem(className, style) {
    let div = document.createElement("div");
    div.SetStyleObject(style);
    div.className = className;
    return div;
  }

  function createScrollBar() {
    scrollbar = CreateScrollElem("scrollbar", styles.scrollbar);
    scrolltrack = CreateScrollElem("scrolltrack", styles.scrolltrack);
    scrollthumb = CreateScrollElem("scrollthumb", styles.scrollthumb);
    scrolltrack.appendChild(scrollthumb);
    scrollbar.appendChild(scrolltrack);
    wrapper.appendChild(scrollbar);
    SetThumbHeight();
    SetScrollEvents();
  }

  function SetThumbHeight() {
    thumbHeight = scrollbar.clientHeight * (wrapper.clientHeight / content.clientHeight);
    scrollthumb.style["height"] = thumbHeight + "px";
  }

  function SetThumbPosition() {
  /*
    my problem below
  */
    let scrollAmount = (window.mouseY - ((scrollbar.clientHeight) - window.clickPos));
    scrollthumb.style["top"] = clamp(scrollAmount, 0, scrollbar.clientHeight - thumbHeight) + "px";
  }

  function SetScrollEvents() {
    scrollthumb.addEventListener("mousedown",
      function(e) {
        window.clickPos = e.pageY;
        window.addEventListener("mousemove", GetMousePos = (e) => {
          window.mouseY = e.pageY
        });
        MousePos = setInterval(SetThumbPosition, 16);
      }
    )
    window.addEventListener("mouseup",
      function(e) {
        window.removeEventListener("mousemove", GetMousePos)
        clearInterval(MousePos)
      }
    )
  }
  createScrollBar();
}
const content = document.getElementById("content");
const wrapper = document.getElementById("wrapper");

SetScrollbar(wrapper, content)
#wrapper {
  height: 150px;
  width: 250px;
  overflow: hidden;
  position: relative;
}
#content {
  position: absolute;
}
<div id="wrapper">
  <div id="content">
    <ul>
      <li> helloworld</li>
      <li> helloworld </li>
      <li> helloworld </li>
      <li> helloworld </li>
      <li> helloworld</li>
      <li> helloworld </li>
      <li> helloworld </li>
      <li> helloworld </li>
      <li> helloworld</li>
      <li> helloworld </li>
      <li> helloworld </li>
      <li> helloworld </li>
    </ul>
  </div>
</div>