Uncaught (in promise) TypeError: document.getElementById(..) is null

I am relatively new to JS and HTML however I cannot understand how to fix the issue I am having, I assumed the issue is the script running before the page has loaded so have tried however I’m unsure what else I can do to fix it. I am trying to use a link found using the JS script and use it for an image in HTML. Using the console on the browser I keep getting the error “Uncaught (in promise) TypeError: document.getElementById(…) is null”

Any help would be appreciated.

MY JS



let accName = "aimxoo";
let accTag = "5600";
let region;
let puuid;
let playercard;
let character;
let mapname;

async function getInfo(accName, accTag){
    let link = "https://api.henrikdev.xyz/valorant/v1/account/" + accName + "/" + accTag + "?force=false";
    try {
        const response = await fetch(link)
        const info = await response.json();
        region = info.data.region;
        puuid = info.data.puuid;
    } catch(err) {
        console.error("ERROR1");
    }
}

async function getMatchr(region, puuid) {
    var mymatchid;
    let link = 'https://api.henrikdev.xyz/valorant/v1/by-puuid/lifetime/mmr-history/' + region + '/' + puuid;
    try {
        const response = await fetch(link)
        const info = await response.json();
        mymatchid = info.data['0'].match_id;
        mapname = info.data['0'].map.name;

    } catch(err) {
        console.error("ERROR2");
    }
    link = 'https://api.henrikdev.xyz/valorant/v2/match/' + mymatchid;
    try {
        const response = await fetch(link)
        const info = await response.json();
        var player = info.data.players.all_players;
        var y;
        for (let x = 0; x <20; x++){
            if(player[x].puuid == puuid) {
                y = x;
                x=20;
            };
        }
        var myplayer = player[y];
       character = myplayer.character;
    } catch(err) {
        console.error("ERROR3");
    }
}

async function getPlayerCard(puuid){
    let link = "https://api.henrikdev.xyz/valorant/v1/by-puuid/account/" + puuid;
    try {
        const response = await fetch (link)
        const info = await response.json();
        playercard = info.data.card.small;
    } catch(err) {
        console.error("ERROR4");
    }
};

async function placePlayerCard(){
    await getPlayerCard (puuid);
    document.getElementById("player-card").src = playercard;
}

async function runInfo() {
   await getInfo(accName, accTag);
   await getMatchr(region, puuid);
   await placePlayerCard();
   console.log(playercard);

}



window.addEventListener("DOMContentLoaded", runInfo);
runInfo();

and this is
MY HTML

<body>
    <div class="overview">
        <img src="" id="player-icon" width="100px">

    </div>

    <script src="player-data.js" defer></script> 
</body>

</html>

Function to remove spacing

I have boolean field like below:

enter image description here

which actually remove spacing from whatever comes at bottom and following is my code:

export default function CallToAction({ removeSpace, ...props }) {
  let defaultMargin = getDefaultComponentMargin(removeSpace);

  return (
    <div
      className={classNames(
        "cta text-center mx-6 md:mx-auto",
        {
          [`${defaultMargin}`]: true,
        },

and remove space function which actually called is below:

export function getDefaultComponentMargin(removeSpace = false) {
  if (removeSpace === true) {
    return "mb-0";
  }

  return "mb-24 xs:mb-40";
}

but unable to remove space from bottom.
Any help would be highlighly appreciated!

How can I do a tag filter using js?

I am trying to filter my projects by using spans as tag. There are tags “segundo”, “evento”, etc… I want the user to type “projeto” in the search bar and then only projects with the tag “projeto” show up.

//search bar
const searchInput = document.getElementById("searchInput");
const projectsShow = document.querySelectorAll(".card");
searchInput.addEventListener("input", function() {
  const searchTerm = searchInput.value.toLowerCase();
  projectsShow.forEach(projectCard => {
    const name = projectCard.querySelector(".card .astro-NYR2HY6C span").textContent.toLowerCase();
    if (name.startsWith(searchTerm)) {
      projectsShow.style.display = "block";
    } else {
      projectsShow.style.display = "none";
    }
  });
});
<input type="text" id="searchInput" aria-label="Pesquise por meus projetos." placeholder="Pesquise por meus projetos..." autocapitalize="off" autocomplete="off" class="astro-S3GEF3U7">

<article class="card astro-WSY3ECDU">
  <a class="cardlink astro-WSY3ECDU" href="./segundo/indicacoesback">
    <div class="content astro-WSY3ECDU">
      <div class="text astro-WSY3ECDU">
        <div class="header astro-WSY3ECDU">
          <h2 class="title astro-WSY3ECDU">Indicações de Backend</h2>
          <span class="date astro-WSY3ECDU">2023</span>
        </div>
        <p class="astro-WSY3ECDU">Este site foi desenvolvido com o objetivo de apresentar indicações de conteúdo relacionado ao desenvolvimento backend.</p>
      </div>
      <div class="astro-NYR2HY6C tags">
        <span class="astro-HL5A4E72" id="segundo">segundo</span>
        <span class="astro-HL5A4E72">tec</span>
      </div>
    </div>
  </a>
</article>

StreamingTextResponse doesn’t working correctly in production

Code which I shared – is api route in Next.js
In dev mode, all working as I expected, but in production, the response seems like static response, so data is sending not dynamically, just like one part

I’m not sure why that happens

On the client side it handled by TextDecoder class, I get chunks with text from api route and add them to state

So as I said, in the dev mode all working like readable stream response, but in production not

used libraries langchain and ai

import { ChatOpenAI, ChatOpenAICallOptions } from "langchain/chat_models/openai"
import { PromptTemplate } from "langchain/prompts"
import { BytesOutputParser } from "langchain/schema/output_parser"
import { StreamingTextResponse } from "ai"
import { cookies } from "next/headers"
import { NextRequest, NextResponse } from "next/server"

export async function POST(req: NextRequest): Promise<StreamingTextResponse> {

    if (!cookies().has(/*property_name*/)) {
        return NextResponse.json(null, { status: 401, statusText: "Unauthorized" })
    }
    // Request body
    const body: AssistantPayload = await req.json()
    // Messages variable
    let messages: Message[] = body.messages
    // Initialize chat model instance
    const model: ChatOpenAI<ChatOpenAICallOptions> = new ChatOpenAI({
    // ... config properties
    })
    // Parser instance
    const outputParser = new BytesOutputParser()

    const prompt = PromptTemplate
        .fromTemplate(/* I can't share it. It's just system prompt */)

    const history = JSON.stringify( // Create history JSON
        messages.map(m => /* creating required history structure as string */)
    const content = body.prompt // New user message
    const chain = prompt.pipe(model).pipe(outputParser)

    const stream = await chain.stream({ history, content }) // Create readable stream

    return new StreamingTextResponse(stream) // Readable stream response
}

Web: Progressbar with multiple steps/segments using Bootstrap

I want to create a similar progressbar like this on my WebApp. I am using PHP (Laravel) as a Framework with Bootstrap 5.3.
Wanted Progressbar

It results from this JSON which is periodically written to the DB from another Application. So “Actual” is increasing continously.

    "Actual": 121,
    "Steps": [
        0,
        3600,
        7200,
        18000,
        36000,
        72000
    ]

The best I was able to create is this:
My Progressbar

<div class="progress-stacked">
  <div class="progress" role="progressbar" aria-label="Segment one" aria-valuenow="121" aria-valuemin="0" aria-valuemax="3600" style="width: 3.075%">
    <div class="text-dark progress-bar bg-info  "></div>
  </div>
  <div class="progress" role="progressbar" aria-label="Segment one" aria-valuenow="0" aria-valuemin="3600" aria-valuemax="7200" style="width: 6.125">
    <div class="text-dark progress-bar bg-light  "></div>
  </div>
  <div class="progress" role="progressbar" aria-label="Segment one" aria-valuenow="0" aria-valuemin="7200" aria-valuemax="18000" style="width: 12.5%">
    <div class="text-dark progress-bar bg-light  "></div>
  </div>
  <div class="progress" role="progressbar" aria-label="Segment one" aria-valuenow="0" aria-valuemin="18000" aria-valuemax="36000" style="width: 25%">
    <div class="text-dark progress-bar bg-light  "></div>
  </div>
  <div class="progress" role="progressbar" aria-label="Segment one" aria-valuenow="0" aria-valuemin="36000" aria-valuemax="72000" style="width: 50%">
    <div class="text-dark progress-bar bg-light  "></div>
  </div>
</div>
.progress {
    border-right: .5px solid black;
    border-radius: unset;
}
.progress-stacked {
    margin: 0 15px;
    width: unset;
}

I also didn’t find any suitable css/js framework or anything like that for it

bus tickets reservation system with javascript alogorithms

This is my use case
The bus goes from point A to point D via B and C. The Bus goes only one way and there is no return.
This means the bus goes as follows A-B, B-C, C-D.

Passengers can get onboard from A,B and C.
All the possible bus ticket options are as follows
A-B, A-C,A-D,B-C,B-D,C-D

bus has 40 seats. 4 seats in a row named as 1A,1B,1C,1D,2A,2B…

I need to write a function to check availability and reserve bus tickets with the given reservation ID. All the code should be in JS. This assignment is for a coding challenge.

I have approached the problem this way

  1. Create a class called Bus

  2. Map all the possible bus ticket scenarios to a object like this

    this.reservations = {
    “A-B”: [],
    “A-C”: [],
    “A-D”: [],
    “B-C”: [],
    “B-D”: [],
    “C-D”: [],
    };

  3. Define another object called complexPaths. complexPath is where you can not go point x to y without passing another points. Eg:- A-C is a complex path, Because B is in middle. Where A-B is not a complex path.

    this.complexPaths = {
    “A-C”: [“A-B”, “B-C”],
    “A-D”: [“A-B”, “B-C”, “C-D”],
    “B-D”: [“B-C”, “C-D”],
    };

  4. If the reservation is for simple path I just fill reservations object’s relevant array with n number of elements. Where n being the number of seats. Eg:- A-B:['reser1','reser1','reser1','reser1','reser1']

  5. If it is a complex path I fill not only that array also I fill related arrays as well. Eg:- A-C 5 tickets
    A-C:['reser2','reser2','reser2','reser2','reser2'] A-B:['reser2','reser2','reser2','reser2','reser2'] B-C:['reser2','reser2','reser2','reser2','reser2'] The reason why I am doing that is if I leave B-C, A-B empty other call mark reservations for those. Since the route is occupied form A-C this shouldn’t happen.

class Bus {
  constructor() {
    this.seats = Array(40).fill(false); // Initializing all seats as available
    this.reservations = {
      "A-B": [],
      "A-C": [],
      "A-D": [],
      "B-C": [],
      "B-D": [],
      "C-D": [],
    };
    this.complexPaths = {
      "A-C": ["A-B", "B-C"],
      "A-D": ["A-B", "B-C", "C-D"],
      "B-D": ["B-C", "C-D"],
    };
  }

  checkAvailability(route, numOfSeats) {
    let totalReservedSeats = 0;

    if (this.complexPaths.hasOwnProperty(route)) {
      this.complexPaths[route].forEach((simplePath) => {
        totalReservedSeats += this.reservations[simplePath].length;
      });
    } else {
      totalReservedSeats = this.reservations[route].length;
    }

    const remainingSeats = 40 - totalReservedSeats;
    return remainingSeats >= numOfSeats;
  }

  updateComplexPaths(reservationId, complexPath, numOfSeats) {
    this.complexPaths[complexPath].forEach((simplePath) => {
      this.reservations[simplePath] = this.reservations[simplePath].concat(
        Array(numOfSeats).fill(reservationId)
      );
    });
  }

  reserveSeat(route, numOfSeats, reservationId) {
    if (!this.checkAvailability(route, numOfSeats)) {
      return "Seats not available for this route";
    }

    const availableSeats = this.seats
      .map((seat, index) =>
        !this.reservations[route].includes(index) ? index : -1
      ) // Find available seats for this route
      .filter((index) => index !== -1);

    if (availableSeats.length < numOfSeats) {
      return "Seats not available for this route";
    }

    const selectedSeats = availableSeats.slice(0, numOfSeats);

    selectedSeats.forEach((seatIndex) => {
      this.seats[seatIndex] = reservationId;
      this.reservations[route].push(reservationId);
    });

    // Update all related simple paths with the same reservation
    if (this.complexPaths.hasOwnProperty(route)) {
      this.updateComplexPaths(reservationId, route, numOfSeats);
    }

    return `Successfully booked ${numOfSeats} seats for ${route}`;
  }
  printReservations() {
    console.log(this.reservations);
  }
}

// Unit tests
let bus = new Bus();

console.log(bus.reserveSeat("C-D", 20, "Reservation2"));
bus.printReservations();
console.log(bus.reserveSeat("B-D", 20, "Reservation1"));
bus.printReservations();
console.log(bus.checkAvailability("C-D", 1) ? "Available" : "Not available");

The above code seems working. I tested with some unit tests as well. but has one issue.
Right now if the user make a reservation for 5 tickets, It will come as common reservationid. But want I want is to return booked seats numbers along with the reservationid like this

{
id:"reser3",
seats:["1A,1B,1C"]

}

How can I do this with JavaScript? Also, this is a workaround solution. Should be a better way to address this issue here. How can I improve the current code as well?

I need a some help i’m beginner In ReactJs Routes and navigation

i need a some help i’m learning ReactJs In Online and im creating one website task for my self. and i stuck in 30% in that task any experts kindly help to complete my task.

I’ll Attach my react app image and reference page image

My React App Image:
This is my react i’m stuck right here

Reference page Image:
This Reference what i’m going to do

I need the same like this. when i click the fullstack Development it will go to next route and the banner image should be change. and i need the below menu list same like this i’ll attach my code also please help me.
I have Attached My code Link — https://stackblitz.com/edit/stackblitz-starters-pkgqbj?file=src%2FApp.js
This My Code I'm Stuck Here Correct my code

why is my programmatically generated jsx elements shows different styles even with exact same css?

This might be a weird question but i noticed my styles applied to the same jsx elements shpwed different with only different data.

so i generated the details page for each country by calling to an api and get the results back.

  const countryElement = (
    <div className={darkMode?'details-country-container dark':'details-country-container'}>
      <div className='flag'>
        <img src={country.flags.png}></img>
      </div>
      <div className='details'>
        <h2>{country.name}</h2>
        <div className='info'>
          <p><b>Native name: </b>{country.nativeName} </p>
          <p><b>Top Level Domain:</b> {country.topLevelDomain} </p>
          <p><b>Population: </b>{country.population} </p>
          <p><b>Currency: </b>{currenciesEl}</p>
          <p><b>Region:</b> {country.region} </p>
          <p><b>Sub region: </b>{country.subRegion} </p>
          <p><b>Languages: </b>{languagesEl}</p>
          <p><b>Capital: </b>{country.capital} </p>
        </div>
        <div className='border-countries'>
          <p><b>Border Countries:</b></p>
          <div className='buttons'>{borderCountriesElements}</div>
        </div>
      </div>
    </div>
  )

and i have a styles for them


.details-country-container {
    overflow-x: hidden;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    column-gap: 50px;
    font-size: 80%;
    margin: 50px 0;
    justify-items: center;
    align-items: center;
}

.details-country-container .details {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    line-height: 130%;
}

.details .info {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    column-gap: 30px;
    margin: 30px 0px;
}

.details .buttons {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, auto));
    column-gap: 10px;
    row-gap: 10px;
    margin: 10px 0 0 0;
}

.details .buttons button {
    width: 100px;
}

but then when I check, different country page would look different.

for example, Luxemburg page is like this, the flags are centered with a few spaces horizontally and the border countries have 4 in a row

luxemburg page, the flags are centered with a few spaces horizontally and the border countries have 4 in a row

but the page for germany is different, there is a spaces horizontally for the flag and the border countries buttons only have 2 in one row…

the page for germany is different, there is a spaces horizontally for the flag and the border countries buttons only have 2 in one row...

but they are essentially the same jsx element, so what might have i done to make them appear different?

I have an issue on iOS, Android devices when loginPopup() microsoft

In Chrome, when the account selection window appears but the requested page is not found.

I am using @azure/msal-browser": "^3.1.0 and @azure/msal-react": "^2.0.3"

auth: {
  clientId: CLIENT_ID_MS,
  redirectUri: REDIRECT_URI,
  authority: `https://login.microsoftonline.com/${TENANT_MS}`,
},
cache: {
  cacheLocation: "sessionStorage",
  temporaryCacheLocation: "sessionStorage",
  storeAuthStateInCookie: false,
  secureCookies: false,
  claimsBasedCachingEnabled: true,
},

Lose ‘text-selection’ functionality after custom implementation for PSPDFKIT

I have a Reactjs project that implements PSPDFKIT as a pdfviewer. We are adding custom logic according to our needs. We need for annotations when the mouse pointer over them to open a popup/modal with some information/data we pass to it. This needs to happen smoothly when someone ‘stop moving’ its mouse on a highlight/annotation. So we add the logic as in the code I have below, but we have a problem. Although the process I mentioned before works fine, we lose some actions like the ‘text selection’ from PSPDFKIT when we need to make a text selection within an existing annotation (we have multiple annotations that are merged). I think our problem is the ‘node’ element we create to have the additional functionality – listeners as PSPDFKIT documentation refers. Any opinion on how to solve this? Or a better approach with the code provided? Thank you!

customRenderers: {
                Annotation: ({annotation}) =>{
                    if (
                    annotation instanceof PSPDFKit.Annotations.TextAnnotation ||
                    annotation instanceof PSPDFKit.Annotations.MarkupAnnotation ||
                    annotation instanceof PSPDFKit.Annotations.LinkAnnotation ||
                    annotation instanceof PSPDFKit.Annotations.HighlightAnnotation ||
                    annotation instanceof PSPDFKit.Annotations.UnderlineAnnotation
                    ) {
                    const node = instance.contentDocument.createElement("div");
                    node.classList.add('myAnnotationCustom')
                    node.dataset.annotationId = annotation.id;
                    node.style.cssText = "position: absolute; width: 100%; height: 100%;pointer-events: all;";
                    node.innerHTML = `<div data-title="${annotation.id}"></div>`;


                    /**
                     * Function that triggered from mouse enter event
                     * @param {*} e
                     * @returns
                     */
                    const mouseoverListener = async function (e) {
                        e.preventDefault();
                        e.stopPropagation();

                        // if match the conditional means that we have another opened annotation and return the value
                        // openedAnnotationId.current is null at first time and when we close the popup and clear the popUpState
                        if(openedAnnotationId.current !== null && openedAnnotationId.current !== annotation.id) return
                        if(isPopupOpened.current) return
                        if (annotation) {
                            mouseStopActionHasAnnotation.current = true;
                        }
                    };

                    /**
                     * Function that triggered from mouse leave event
                     * @param {*} e
                     */
                    const mouseLeaveListener = (e) => {
                        if(isPopupOpened.current) return
                        e.preventDefault();
                        e.stopPropagation();
                        mouseStopActionHasAnnotation.current = false;
                    }

                    /**
                     * Function that triggered when mouse moving stops and you are inside an annotation node
                     */
                    const handleOpenPopup = () => {
                        setCurrentAnnotation(annotation);
                        openedAnnotationId.current = annotation.id;
                        isPopupOpened.current = true;
                        setShowPopup(true)
                    }

                    /**
                     * Function that triggered when mouse moving stops and you are out of annotation node
                     */
                    const handleCancelPopup = () => {
                        if(!isPopupOpened.current) {
                            setCurrentAnnotation(null);
                        }
                    }

                    /**
                     * Function that triggered with mousemove event and when stop moving mouse in triggers the logic inside setTimeout
                     * @param {*} event
                     */
                    const handleMouseMove = (event) => {
                        if(isPopupOpened.current) return
                        clearTimeout(timer);
                        timer = setTimeout(() => {
                            if(annotation && mouseStopActionHasAnnotation.current) {
                                const mousePosition = {
                                    event: event,
                                    x: event.pageX - 80,
                                    y: event.pageY - 120
                                }
                                setMousePosition({
                                    top: mousePosition.y,
                                    left: mousePosition.x
                                })
                                handleOpenPopup()

                            } else {
                                handleCancelPopup();
                            }
                            node.removeEventListener("mousemove", handleMouseMove);
                        }, 500);
                    }

                    node.addEventListener("mouseenter", mouseoverListener, {once: true});
                    node.addEventListener("mouseleave", mouseLeaveListener, {once: true});
                    node.addEventListener('mousemove', handleMouseMove);

                    return {
                        node,
                        append: true,
                        };
                    }
                }
            }