how do i make a page automatically render an image when clicked

I am workin on an e commerce website . I want to create this feature but i am having a little difficulty . When a user clicks on an image , it redirects them to a page that contains more details about the selected item and a little carousel that enables the user see different angle of the cloth selected . I dont want tp hard code this for all features on the project . I would love to create a component that cam serve this purpose . I am using Next js for React , Thank you

here is my code
This is an example of a shirt component file . I
import Image from “next/image”;

import products from "../product/MenShoes/MenShoes";
import Items from "../app/Items";


function ShirtComp ({}) {

    return (

        <div className="grid grid-flow-row-dense md:grid-cols-2 lg:grid-cols-3">
            {
                products.map(({id, name, price, size, image }) => {
                    return <Items
                        key={id}
                        id={id}
                        name={name}
                        price={price}
                        size={size}
                        image={image}
                    />
        
                })
            }
        </div>
    )
}
export default ShirtComp 

THIS IS THE ITEM FILE

import Image from "next/image";
import { useDispatch } from "react-redux";
import { addToBasket } from "../slices/basketSlice";

import { useRouter } from "next/router";

function Items({ id, name, price, size, image } ) {
 
    const router = useRouter();

 
 
    const dispatch = useDispatch();
 
 
 
    const addItemToBasket =()=>{
        const product = {
            id,
           image,
            name,
            size,
            price,
        };

        dispatch(addToBasket(product))
   }
    return (
        <div className="relative flex flex-col m-5 bg-white z-30 p-10">
            <img  onClick={() => router.push('/Description')} src={image} height={400} width={400} objectFit="contain" className="cursor-pointer"/>
            <p className="my-3 pr-5">{name}</p>
            <p className="mb-5">{size}</p>
            <p className="mb-5"> ${price}</p>
            <button onClick={addItemToBasket} className="mt-auto button">Add to cart</button>
            
        </div>
        
    )
 

}

export default Items

How di i please make on click of the image tag . the image clicked is automatically rendered in another page , I hope who ever reads this gets what i am talking about .

In JavaScript (specifically node.js) how can I generate a reusable list of dynamically generated and incremented variable names using a for loop?

I’m creating a custom Gutenberg block using node.js and REACT. Eventually this will be a Bootstrap slider that can have slides added dynamically. For each slide the user needs to upload a video or image. I am doing this using the built-in component that is part of @wordpress/block-editor.

I’ve added 3 <MediaUpload> components in the <InspectorControls> that will display in the right block controls column in WordPress.

The work by calling an “onChange” function that updates the backgroundImage attribute that is originally set in block.json.

<InspectorControls>
    <PanelRow>
        <fieldset class="media-upload">
        <strong>Select slide 1 video or image:</strong>
            <MediaUpload
                onSelect={onImageSelect}
                type={ [ 'image', 'video' ] }
                value={backgroundImage} 
                render={({ open }) => (
                    <button onClick={open}>
                        Upload Image!
                    </button>
                )}
            />
        </fieldset>
        <fieldset class="media-upload">
        <strong>Select slide 2 video or image:</strong>
            <MediaUpload
                onSelect={onImageSelect}
                type={ [ 'image', 'video' ] }
                value={backgroundImage}
                render={({ open }) => (
                    <button onClick={open}>
                        Upload Image!
                    </button>
                )}
            />
        </fieldset>
        <fieldset class="media-upload">
        <strong>Select slide 3 video or image:</strong>
            <MediaUpload
                onSelect={onImageSelect}
                type={ [ 'image', 'video' ] }
                value={backgroundImage}
                render={({ open }) => (
                    <button onClick={open}>
                        Upload Image!
                    </button>
                )}
            />
        </fieldset>
    </PanelRow>
</InspectorControls>

The function looks like this

const onImageSelect = ( imageObject ) => {
        setAttributes( { backgroundImage: imageObject.url } )
}

The problem is that in order for this to work I would have to create a separate function for every instance of the MediaUpload component, for example, onImageSelect1, onImageSelect2, onImageSelect3 and these would have to have the corresponding backgroundImage attribute incremented as well, e.g. backgroundImage1, backgroundImage2, backgroundImage3.

This is ok with a small case scenario like this, but I will add many more user controls for all kinds of aspects of the slider, so I need to know how I can do this in as few lines of code as possible.

I need to make the onImageSelect function dynamic. I’ve tried adding a “media-upload” class to each instance of the MediaUpload component and then use a for loop to loop through these and create incremented reusable variable names. I might be way of the mark here? I’m really struggling to write the loop; this is the result from my experimentation so far.

var thisClassName = 'media-upload';
    var items = document.getElementsByClassName(thisClassName);
    for (var i=0; i < items.length; i++) {
        items[i].setAttribute("id", "onImageSelect" +i);
        var hereItIs = items[i].id
        console.log(hereItIs)
    }

The output of the above was unexpected and I also can’t access any of the variable values inside the loop because they aren’t exposed to scope. I guess my main question is how can I generate a reusable list of dynamically generated and incremented variable names using a for loop?

My aim is to have

const onImageSelect1 = ( imageObject ) => {
        setAttributes( { backgroundImage1: imageObject.url } )
}

const onImageSelect2 = ( imageObject ) => {
        setAttributes( { backgroundImage2: imageObject.url } )
}

const onImageSelect3 = ( imageObject ) => {
        setAttributes( { backgroundImage3: imageObject.url } )
}

but, without writing it like this. I want a single function where onImageSelect and backgroundImage3 are being dynamically incremented based upon the number of MediaUpload components (or classes of its wrapper) the script finds on the page.

Removing and displaying Item dynamically from localstorage

I am new to React.js and working on a project finds deals for games, this is my wishlistdata component, my issue is that whenever I delete item from wishlist it gets removed from localstorage but the card doesnt disappear until the page is reloaded, also help me if my code is unclean. Thanks in advance.
Here is my code :

import Wishlist from "./Wishlist";
import "./Wishlist.css";
import "animate.css";
import axios from "axios";

const WishlistData = () => {
  const [gamedet, setGameDet] = useState([]);
  const [loaded, setLoaded] = useState(false);
  const [stores, setStores] = useState([]);
  const [price, setPrice] = useState([]);
  const [wishlist, setWishlist] = useState([]);

  useEffect(() => {
    setWishlist(localStorage.getItem("Wishlist") ? JSON.parse(localStorage.getItem("Wishlist")):[])
    },[setWishlist])

  const RemoveFromWishlist = (id) => {
     let newList = wishlist.filter((game) => game.gameID !== id);
    setWishlist(localStorage.setItem("Wishlist", JSON.stringify(newList)));
    localStorage.setItem("Wishlist", JSON.stringify(newList));
    console.log("id", wishlist);
    console.log("newlist", wishlist);
  };
  const DET_URL = `https://api.rawg.io/api/games`;
  useEffect(() => {
    let isCancelled = false;
    const RAWGdet = () => {
      wishlist && wishlist.map((game, index) => {
        return axios({
          url: `https://cors-anywhere.herokuapp.com/${DET_URL}/${game.gameID}?key=${process.env.REACT_APP_RAWG_KEY}`,
          headers: {
            "X-Requested-With": "XMLHttpRequest",
          },
          method: "GET",
        }).then((res) => {
          if (!isCancelled) {
            setGameDet((gamedet) => gamedet.concat(res.data));
          }
          setLoaded(true);
        });
      });
    };
    RAWGdet();
    return () => {
      isCancelled = true;
    };
  }, [DET_URL, wishlist]);

  console.log("wish", wishlist);
  useEffect(() => {
    let isCancelled = false;
    const CSPrice = () => {
      wishlist && wishlist.map((game, index) => {
        return axios({
          url: `https://cors-anywhere.herokuapp.com/${DET_URL}/${game.slug}/stores?key=${process.env.REACT_APP_RAWG_KEY}`,
          headers: {
            "X-Requested-With": "XMLHttpRequest",
          },
          method: "GET",
        }).then((res) => {
          if (!isCancelled) {
            setStores((stores) => stores.concat(res.data));
          }
          setLoaded(true);
        });
      });
    };
    CSPrice();
    return () => {
      isCancelled = true;
    };
  }, [DET_URL, wishlist]);

  let stm = [];

  stores
    .map((steam) => {
      return steam.results;
    })
    .filter((item) => {
      return item.map((id) => {
        return id.store_id === 1 ? stm.push(id.url) : <>{null}</>;
      });
    });
  // console.log("in", stm);
  let idmain = [];
  stm.map((steamid) => {
    return steamid.split("/").map((item) => {
      return idmain.push(item);
    });
  });

  useEffect(() => {
    return (
      <>
        { wishlist && wishlist.map((game, index) => {
          return (
            <div key={index}>
              {axios
                .get(
                  `https://www.cheapshark.com/api/1.0/deals?storeID=1,7,8,11,13,25&steamAppID=${game.steamID}`
                )
                .then((res) => {
                  setPrice((price) => price.concat(res.data));
                }, setLoaded(true))
                .catch((err) => {
                  console.log("ERR", err);
                })}
            </div>
          );
        })}
      </>
    );
  }, [wishlist]);
let tempArr1 = []
let temparr2= []

// console.log("gam2", tempArr2);

  if (loaded) {
    return (
      <div className="animate__animated animate__slideInDown">
        <div className="wishlist_header">
          <h3>Your Wishlist</h3>
        </div>
        {wishlist.length !== 0 ? (
          price.map((game1) => {
            let temp = {
              "steamAppID" : game1.steamAppID,
              "storeID" : game1.storeID,
              "normalPrice" : game1.normalPrice,
              "salePrice" : game1.salePrice
            };
            return tempArr1.push(temp) && tempArr2.push(temp.steamAppID);
          }) &&
          gamedet.map((game, index) => {
            // console.log("mad2", game.name);
            return (
              <div id="wishlist_ctn" key={index}>
                <Wishlist
                  key={index}
                  title={game.name}
                  steamRatingCount={game.id}
                  // steamRatingPercent={game[0].steamRatingPercent}
                  // savings={game[0].savings}
                  // normalPrice={}
                  // salePrice={salePrice}
                  steamAppID = {gamble2}
                  data={gamble}
                  image={game.background_image}
                  rem={() => RemoveFromWishlist(game.id)}
                />
              </div>
            );
          })
        ) : (
          <div className="wishlist_header">
            <h3>Add Games!!</h3>
          </div>
        )}
      </div>
    );
  } else {
    return (
      <div className="hmm">
        <div className="wishlist_header">
          <h3>Your Wishlist</h3>
        </div>
        <div className="wishlist_header">
          <h3>Loading Games</h3>
        </div>
        );
      </div>
    );
  }
};

export default WishlistData;

Firebase: Error (auth/missing-email) when the email definetly exists. Reactjs

Here is my code:

function loginWithEmailHandler() {
        signInWithEmailAndPassword(auth)
        .then((result) => {
            const user = result.user;
            console.log(user.email, user.displayName);
            navigate("/");
        })
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            setMode("INCORRECT");
            console.log(errorCode, errorMessage);
        });
    }

When I run this function in my LoginForm.js it gives the error stated in the title. I don’t know how I could check if it checking for the correct email or not so I am a bit stuck here.

Modal not showing up when linking to new page

I am trying to link a modal in a different page. But when I click the button to toggle modal, nothing comes up. I have two files: courses.php and addCourses.php. course.php is where the button to click the modal is from, and addCourses.php is the modal form that should appear but dosen’t

courses.php

 <div class="btn mb-2 mb-md-0">
      <a href='addCourses.php' class="btn btn-sm btn-gray-800 d-inline-flex align-items-center animate-up-2" data-bs-toggle="modal" data-bs-target="#modal-form"> Add Course </a>

      <!-- Modal -->
      <div class="modal fade" id="modal-form" tabindex="-1" role="dialog" aria-labelledby="modal-form" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
          <div class="modal-content rounded bg-white">
          </div>
        </div>
      </div>
    </div>

addCourses.php

  <div class="modal-body p-0">
    <div class="card bg-white p-4">
      <button type="button" class="btn-close ms-auto" data-bs-dismiss="modal" aria-label="Close"></button>
      <div class="card-header border-0 bg-white text-center pb-0">
        <h2 class="h4">Course Info</h2>
      </div>
      <div class="card-body">
        <!-- Form -->
        <form action="courses.php" method="post" class="mt-4">
          <div class="form-group mb-4">
            <label for="course_name">Course name:</label>
            <div class="input-group">
              <span class="input-group-text" id="basic-addon2"><span class="fas fa-hotel"></span></span>
              <input type="text" name="course_name" class="form-control" required>
            </div>
          </div>
          <div class="form-group mb-4">
            <label for="number">Course number:</label>
            <div class="input-group">
              <span class="input-group-text" id="basic-addon2"><span class="fas fa-door-open    "></span></span>
              <input type="text" name="number" class='form-control' required>
            </div>
          </div>
          <div class="form-group mb-4">
            <label for="number">Course desciption:</label>
            <div class="input-group">
              <span class="input-group-text" id="basic-addon2"><span class="fas fa-door-open    "></span></span>
              <input type="text" name="desc" class='form-control' required>
            </div>
          </div>

          <div class="form-group mb-4">
            <label for="number">Final grade:</label>
            <div class="input-group">
              <span class="input-group-text" id="basic-addon2"><span class="fas fa-door-open    "></span></span>
              <input type="text" name="grade" class='form-control' required>
            </div>
          </div>
          <div class="row mb-5 mb-lg-5">
            <div class="col-lg-4 col-md-6">
              <div class="form-group mb-4">
                <div class="mb-3">
                  <span class="fw-bold">Currently Enrolled</span>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="checked">
                </div>
              </div>
            </div>
          </div>
          <div class="d-grid">
            <button type="submit" class="btn btn-primary" name="add_course" value="Create Property">Add course</button>
          </div>
        </form>
      </div>
    </div>
  </div>

both files have the same CSS and JS applied to them, so what am I doing wrong?

keyboard events using Javascript

hello am new in coding am having trouble firing this code when i press ‘ArrowUp’.what am i missing.i am using chrome and my IDE is replit

let circle= document.querySelector('.circle')
 function control (event){
if (event.key === 'ArrowUp'){

  console.log('key pressed')
}
 }
 document.addEventListener('keydown',control)

here is the link to my project
https://replit.com/@GwendolineBinya/keyboard-events#script.js

AoC day5, puzzle two – JS, no errors but wrong solution

I am stuck in debug hell. Code works for testdata, not for realdata

I am not loosing any datasets, as far as i can tell

of course i can provide a dataset, if necessary

console.log('day5a')
import { testData, realData} from "./day5data.js";

let data = testData.split('n')
let grid = createGrid(1000,1000)
let allReadings = []

getReadings()
drawLines()

let crossings = countCrossings()
console.log('crossings: ', crossings)


// console.log('hvReading: ', hvReadings)
function drawLines(){
    let x = allReadings.length
    console.log('allReadings.length ', allReadings.length)
    let noneForgotten = true
    allReadings.forEach(reading => {
        let x1= reading[0][0]*1, y1=reading[0][1]*1, x2= reading[1][0]*1, y2=reading[1][1]*1

        if     (x1 > x2 && y1 > y2) drawX1andY1bigger(x1, y1, x2, y2)
        else if(x1 > x2 && y1 < y2) drawX1andY2areBigger(x1, y1, x2, y2)
        else if(x1 < x2 && y1 < y2) drawX2andY2areBigger(x1, y1, x2, y2)
        else if(x1 < x2 && y1 > y2) drawX2andY1areBigger(x1, y1, x2, y2)
        else if(y1===y2){
            if(x1 > x2) drawHorizontal(y2,x2,x1)
            else drawHorizontal(y2,x1,x2)
        } else if(x1===x2) {
            if(y1>y2) drawVertical(x1, y2, y1)
            else drawVertical(x1, y1, y2)
        }
        else {
            console.log(reading, ' DONT FORGET ME')
            noneForgotten = false
        }
    })
    console.log(noneForgotten, ' noone')
}

// diagonal drawings
function drawX2andY1areBigger(x1, y1, x2, y2){
    for(;x1<=x2;x1++,y1--){
        grid[x1][y1]++
    }
}

function drawX2andY2areBigger(x1, y1, x2, y2){
    for(;x1<=x2;x1++,y1++) {
        grid[x1][y1]++
    }
}

function drawX1andY2areBigger(x1, y1, x2, y2){
    for(;x1>=x2;x1--,y1++) {
        grid[x1][y1]++
    }
}


function drawX1andY1bigger(x1, y1, x2, y2){
    for(;x1>=x2;x1--, y1--) {
        grid[x1][y1]++
    }
}

// horizontal drawings
function drawHorizontal(row, startCol, endCol){
    for (let i = startCol; i <= endCol ; i++) {
        grid[row][i]++
    }
}
function drawVertical(col, startRow, endRow){
    for (let i = startRow; i <= endRow; i++) {
        grid[i][col]++
    }
}

function getReadings(){
    for (let i = 0; i < data.length; i++) {
        data[i] = data[i].split(' -> ')
        for (let j = 0; j < data[i].length; j++) {
            data[i][j] = data[i][j].split(',').map(Number)
        }
        allReadings.push(data[i])
    }
}

function createGrid (cols, rows) {
    let grid = []
    for (let i = 0; i < cols; i++) {
        grid[i] = []
        for (let j = 0; j < rows; j++) {
            grid[i][j] = 0
        }
    }
    return grid
}


function countCrossings(){
    let crossings = 0
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[i].length; j++) {
            if(grid[i][j] >=2) {
                crossings++
            }
        }
    }
    console.log('crossings', crossings)
    return crossings
}

wont let me post without more explanation, so: i am creating a two dimensional array, filled with zeros in createGrid()
i import the dataset, split it at linebrack, split every array in that at the ‘ -> ‘ arrow, split every array in that at the semicolon. i’m mapping it to number, just to be sure

after that, i draw “lines” at drawLines. depending on the coordinates, i raise the grid[i][j]++ in the functions described from line 44 to line 80

will provide further informationbs if nessecary

useEffect dependancy array

I’m using customHook to fetch data from an API.

const useFetch = () => {
   const dispatch = useDispatch();
   return async (callback, ...props) => {
      try {
         return await callback(...props);
      } catch (error) {
         const { msg } = error.response?.data || "Something went wrong";
         dispatch(showModal(msg));
         setTimeout(() => dispatch(hideModal()), 3000);
      }
   };
};

and using it inside useEffect

const customFetch = useFetch();
useEffect(() => {
      (async () => {
         const data = await customFetch(fetchUsers, token);
         if (data) setUsers(data.user);
      })();
   }, [token]);

But eslint is complaining about the missing customFetch dependency. If I add it it will end up in an infinite loop. How can I fix this?

TypeORM entity throwing error when generating migration

I have a simple entity called Picture.ts and is has following content

const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm");

@Entity()
export class Picture {
@PrimaryGeneratedColumn()
id: string;

 @Column()
 name: string;

 @Column()
 path: string;

 @Column()
 is_main: boolean;
}

My tsconfig.json is:

{
   "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "./src/**/*.tsx",
    "./src/**/*.ts"
  ]
}

When try running typeorm migration:generate it throws error like this

Error during migration generation:
/src/src/entity/Picture.ts:3
@Entity()
^

SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at /src/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:39
at Array.map (<anonymous>)
at importClassesFromDirectories (/src/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:10)

what could be the problem ?

Semicolons make deconstruction assignment problematic in Chrome Javascript Console

I ran the following code in turn in Chrome Javascript Console

{f}={f:3} // it created a new variable f with a value of 3
{f}={f:3}; // Uncaught SyntaxError: Unexpected token '='

{f}={f:3} // There is a blank line on it,error: Uncaught SyntaxError: Unexpected token '='

Why do they behave differently?

The problem extends from here: object_destructuring – Assignment separate from declaration

Scrollmagic / I want to create a scene in a loop

I’m trying to use Scrollmagic to create an animation that displays text character by character.

I want to create a scene using a for loop, but it doesn’t work.

HTML


    <p class="letter">
    <span>H</span>
    <span>e</span>
    <span>l</span>
    <span>l</span>
    <span>o</span>
    </p>

JS (Doesn’t work)


    var letterElements = document.getElementsByClassName("letter");
    for (var n=0; n < letterElements.length; n++) {
        var scene = new ScrollMagic.Scene({
            triggerElement: letterElements[n],
            triggerHook:0.8,
            offset:100,
            reverse:false
        })
        .on("enter", function (event) {
            $('.letter').eq(n).children('span').each(function(i) { //Maybe this line is the problem
                $(this).delay(20 * i).queue(function() {
                    $(this).addClass('visible').dequeue();
                });
            });
        })
        .addTo(controller);

}

JS (Work)

It works when I write the following without using the for loop.


    var scene = new ScrollMagic.Scene({
        triggerElement: letterElements[0],
        triggerHook:0.8,
        offset:100,
        reverse:false
    })
    .on("enter", function (event) {
        $('.letter').eq(0).children('span').each(function(i) {
            $(this).delay(20 * i).queue(function() {
                $(this).addClass('visible').dequeue();
            });
        });
    })
    .addTo(controller);
    
    var scene = new ScrollMagic.Scene({
        triggerElement: letterElements[1],
        triggerHook:0.8,
        offset:100,
        reverse:false
    })
    .on("enter", function (event) {
        $('.letter').eq(1).children('span').each(function(i) {
            $(this).delay(20 * i).queue(function() {
                $(this).addClass('visible').dequeue();
            });
        });
    })
    .addTo(controller);
    
    ・
    ・
    ・
    ・

Angular routing displaying the same app.component.html

I’m currently using Angular version 13.

As stated by the official documentation, routing should be done by creating a component and routing it like this in the app-routing.module.ts

const routes: Routes = [
{ path: 'first-component', component: 
FirstComponent },
{ path: 'second-component', component: 
SecondComponent },
];

but doing so will render my app.comoponent.html file without actually changing anything. I can see that the url changed, but that’s about it.
Other newer sources consider doing something like

{
path:'mainpage',
loadChildren: () => import('./mainpage/mainpage.module').then(m 
=> m.MainpageModule)
}

and, as the solution above, does not work for me. I’ve also added the <router-outlet></router-outlet> directive, (which was actually already added) but nothing changed. What is currently happening? Thanks!

pubnub removeListener doesn’t trigger on useEffect return

While opening a single chat works flawlessly, entering a chat, then leaving the chat screen and entering the chat again causes double messaging and the listener isn’t being removed despite placing it on the return in useEffect
I’ve even tried the solution in this thread: React Pubnub Chat. Message dublication or no message at all

Hopefully, you guys can help me identify the issue. thanks in advance!

 useEffect(() => {
   
    const listener = {
      message: (envelope: any) => {
        if (envelope) {
          const message = {
            channel: envelope.channel,
            message: {
              ...envelope.message,
            },
            uuid: envelope.publisher,
            timetoken: envelope.timetoken,
          }

          dispatch(setMessage(message))
// this log activates the same amount of times you entered and left the chat, because the listener isn't being removed
          console.log('Message listener activated!') 
        }

        //   setLastTimeToken(message.timetoken)
      },
    }

    pubnub.addListener(listener)
    pubnub.setUUID(employer._id)


    pubnub.fetchMessages(
      {
        channels: [ch],
        count: 100,
      },
      (status, response) => {
        if (response.channels[ch]) {
          dispatch(setMessages(response?.channels[ch]))
        } else {
          dispatch(setMessages([]))
        }
      },
    )
    pubnub.subscribe({ channels: [ch] })

    const usersInfo = channel.split('_')
    if (channel != employer._id && usersInfo[1] !== 'job') {
      const deeberId = usersInfo[0]
      getCandidateById(deeberId).then(res => {
        dispatch(setSelectedChatCandidate(res))
      })
    }
    renderDisplayName()

    return () => {
      pubnub.removeListener(listener) 

      pubnub.unsubscribeAll()
    }

  }, [])

Datatables: Header misaligned with table body when scrolling to the right on reload

I have a datatable which works absolutely fine on page load. It has a horizontal scrollbar as the table width is very large and my first 3 columns are fixed. However, when I refresh the page, and I scroll to the right at the very end, the table header stays fixed and the table body alignment moves to the left such that they are no longer aligned. I removed the left-padding of 17px btw.

Here is the code:

 $(document).ready(function () {
    $('#tblEvents').DataTable({
        destroy: true,
        "scrollX": true,
        "scrollY": "600px",
        "scrollCollapse": true,
        "pageLength": 5,
        fixedColumns: {
            leftColumns: 3
        },
   });

Please help n thanks 🙂

How to mark some of checkbox list value as checked in Angular?

I have a checkbox list with websites. This list is created from 10 values, and I need to mark first 5 elements as checked. How we can do this in Angular? I use Angular Material checkbox.

 <section >
          <p>Value:</p>
          <p *ngFor="let data of websites | async">
            <mat-checkbox [value]="data.name">{{data.name}}</mat-checkbox>
          </p>
</section>

“websites” from *ngForm is an observable in which I get all websites.