Why is my API not rendering correctly after I have fetched correctly? [closed]

I am fetching an API and attempting to display it on my HTML page. I am decently sure that I have fetched it correctly with this code:

const fetchAllPlayers = async () => {
  try {
    const result = await fetch(API_URL);
    const response = await result.json();
    console.log(response);

    return response;

  } catch (err) {
    console.error("Uh oh, trouble fetching players!", err);
  }
};

The console log prints out the information I like. What I am struggling with is displaying it.

const renderAllPlayers = (playerList) => {
  const wrapper = document.getElementById("wrapper");

  response.forEach(player => {
    const card = document.createElement('div');
    card.classList.add('card');

    const nameEle = document.createElement('h1');
    nameEle.textContent = player.name;

    card.appendChild(nameEle);
    wrapper.appendChild(card);
  });
}

This is my attempt at rendering the API, but for some reason, it is not rendering. I have tried multiple ways and this makes sense to me, but I have no idea why it’s not completing.

I’m sorry if this is really simple, I am quite new to this. Any help is appreciated!

EDIT: I am required to use the “playerList” variable I just don’t know how to use it…

What Provider Should I use to Host a Vue website and a separate Python backend? [closed]

I am completely lost on where to host my project. I am creating a Vue website with a frontend (js) and backend (py) that has another separate Python Flask server that is almost an API of sorts that I need to be constantly running 24/7 (which is why I want it to be separate from the main backend so that it doesn’t get interrupted whenever I have to update something).

I tried to use Render, but their free plan puts the server to sleep after 30 min making it slowdown which I don’t want. Their paid plan seems to be $7 per project, when I’m sure there are other hosting sites out there that are the same price for multiple projects.

There’s so much different information on Yt and Google I don’t know what I should use. So my question is, what is a good provider I could use to host this project, with a budget under $10 a month?

How do you switch one image to another using JavaScript?

I have been looking into different ways to use JS to switch from one image to another. I tried using classList.toggle and now eventListener method, which I thought will work just fine but the button is not working in all scenarios. I also want to change the text of the button using .textContent. I realized that some of my syntax is light blue. Wondering what I am missing. I checked the console several times but no issues found.

I tried the declaration function with direct image switch and it worked, but the arrow function with event listener is not working. Which is what I want to use. I am preparing for an interview and need to show I can use the event listener method to switch images.

<!Doctype html>
<html lang="en">
  <head>
    <title>About Us</title>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <h1>ABOUT US</h1>
    <a href="#bottompg">Jump to Bottom Page</a>


    <button id="showGiftCardBtn">
    Open Me
    </button>

    <img id="discountCode" src="images/gift.png.gif" alt="letters and numbers on a white background"  class="code"    style="display:none">

    <script   src="script.js"></script>
  </body>
</html>

JavaScript:

const showGiftCard = document.getElementById("ShowGiftCardBtn");
const showCodeImage = document.getElementById("discountCode");
showGiftCard.addEventListener("click", ()  => {
showCodeImage.style.dispaly = "block";

let cardButton = document.getElementById('showGiftCardBtn')
 console.log(cardButton)
cardButton.textContent = " Your code! 10% off any of our products or services. Thank You For Your Bussiness"
});

antd Calendar duplicates the dates if I use cellRender in React.js

I was trying to reuse the antd calendar component for few months and highlight some specific days on each Calendar ( in light green). To perform this feature, I used cellRender to customize the calendar.

But when I do it, it duplicates the dates on each calendar as below screenshot. And also the dates are not selectable. The other thing is it always keep selected the current date (in dark green) by default. My question is,

  1. How can I keep the default selected date unselected.
  2. How avoid this date duplication?
  3. And still keep the dates selectable as I need ?

calendar_issue_image

These are the utilized package versions:

React version:     "react": "^18.2.0",

antd version:     "antd": "^5.4.6",

The code snippet:

CalendarList.jsx

import React from 'react'
import CalendarCard from './card/CalendarCard'
import dayjs from 'dayjs';
import './CalenderList.css';

let currentMonth = dayjs().month();
const monthsCount = 12;
const days = ['Wednesday', 'Thursday'];

const CalendarList= () => {
  return (
    <div className='CalendarList'>
      {Array.from({ length: monthsCount }, (_, i) => (
        <CalendarCard key={i} month={dayjs().month(currentMonth + i)}  days={days}/>
      ))}
    </div>
  )
}

export default CalendarList

CalendarCard.jsx

import React from 'react';
import { Calendar, theme } from 'antd';
import './CalendarCard.css';

const CalendarCard = ({ month, days }) => {
    const { token } = theme.useToken();

    const dateCellRender = (value) => {
        if (value.month() === month.month()) {
            const dayOfWeek = value.format('dddd');
            if (days.includes(dayOfWeek)) {
                return <div className='highlighted-day'>{value.date()}</div>
            }
        }
        return <div>{value.date()}</div>
    };

    const headerRender = ({ value }) => {
        return (
            <div style={{ padding: '10px', textAlign: 'center', fontSize: '16px', fontWeight: 'bold' }}>
                {value.format('MMMM YYYY')}
            </div>
        );
    }

    const onDateSelect = (value) => {
        console.log(value)
    }

    const wrapperStyle = {
        width: 300,
        border: `1px solid ${token.colorBorderSecondary}`,
        borderRadius: token.borderRadiusLG,
    };

    return (
        <div style={wrapperStyle}>
            <Calendar
                fullscreen={false}
                headerRender={headerRender}
                value={month}
                mode='month'
                onSelect={onDateSelect}
                cellRender={dateCellRender}
            />
        </div>
    )
}

export default CalendarCard

CalendarCard.css

.highlighted-day  {
    background-color: #87d068;
    color: white;
    border-radius: 4px;
}

How do I connect the HM10 to a web app and use it for two-way communication

Last time I posted a problem stating that no matter what I did, the BLE module (what I now know was actually a HC-06) did not work when trying to communicate with a web app. Since then, I have gotten a new HM10 module and replaced the previous HC-06 to try and make it work. To put it simply, it still does not work.

I’ve spent the past few days trying to get this thing to work. I tried logging everything, trying to reduce things to a simpler state, and isolating segments of the code, but it just does not want to work.
First thing I tried was to run the code as is.
Arduino Code:

    #include <SoftwareSerial.h>
    #define BT_RX_PIN 10
    #define BT_TX_PIN 11
    String btdata = " ";
    String screen;
    SoftwareSerial bt(BT_RX_PIN, BT_TX_PIN);

    void setup() {
        Serial.begin(9600);
        bt.begin(9600);
    }
    void loop() {
        ...
        screen = "some string";
        Serial.println(screen);
        bt.print(screen);
        btdata = bt.readString();
        Serial.println(btdata);
    }    

JS Code:

function read(event) {
    console.log("reading");
    let buffer = event.target.value.buffer;
    let view = new Uint8Array(buffer);
    let decodedMessage = String.fromCharCode.apply(null, view);

    let newNode = document.createElement('p');
    newNode.classList.add("received-message");
    newNode.textContent = decodedMessage;

    document.getElementById("terminal").appendChild(newNode);

    let placeholder = document.getElementsByClassName('placeholder');
    if(placeholder.length != 0) placeholder[0].remove();

    console.log(decodedMessage);
}

async function write(event){
    let message = document.getElementById("message-input").value;
    message += 'n';
    let buffer = new ArrayBuffer(message.length);
    let encodedMessage = new Uint8Array(buffer);
    
    for(let i=0; i<message.length; i++){
        encodedMessage[i] = message.charCodeAt(i);
    }

    await serialCharacteristic.writeValue(encodedMessage);
    document.getElementById("message-input").value = null;
}


document.getElementById('connect').addEventListener("click", connect);
document.getElementById('send').addEventListener("click", write);

The idea is to send some string to the web app, have the web app do some stuff with the String sent, then return it. So, it prints to the HM10, then it receives from the HM10. Now, while this is the current form of the code, I did consider some possible reasons why it didn’t work. I tried using bt.available(), (either using a while loop or if statement) but that either resulted in an infinite loop or the same problem as the above code segment.
The output for this code segment was:


some string

some string

some string
...

So, basically it was not managing to receive anything at all. So the btdata was just assigned as the blank string. I checked by highlighting it, there wasn’t even a space, literally just without any characters at all.

Now, taking a look at the Arduino, the TX light does flash whenever I try to send a message with it, but the web app developer console never logs anything. That confuses me even more, since that to me seems like the HM10 is trying to send the string, but it just never reaches the web app even though they are connected.

I did take the code from a github repository my friend recommended to me since he used it and got it to work. So I naturally thought maybe my additional code was causing the issue. I didn’t see how as I didn’t interact with the HM10 outside of the segment shown above, but I was desperate. So I reverted mostly everything back to the way it was as in the original repository (barring a few logging statements), and ran the code again.

Arduino Code:


#include <SoftwareSerial.h>

#define BT_RX_PIN 10
#define BT_TX_PIN 11

SoftwareSerial BT(BT_TX_PIN, BT_RX_PIN);

String message;

void setup() {
  BT.begin(9600);
  Serial.begin(9600);
}

void loop() {
  if(BT.available() ){
    message = BT.readStringUntil('n');
    message += " received";
    BT.println(message);
    Serial.println(message);
  }
}

Now a new issue was popping up. Whenever I tried connecting the HM10 to the web app, there would be an error:
index-93a81548.js:21 Uncaught (in promise) DOMException: GATT Server is disconnected. Cannot retrieve services. (Re)connect first with device.gatt.connect.

Now my previous confusion goes out the window as I am now more confused. I looked up the error (as you do), and found that the most common fix that I could find was restarting Windows or simply retrying. In my case neither fix worked. This confuses me some more as it worked perfectly fine earlier insofar as the connection went, but now it does not even connect.

I tried a few small changes, and looking up the HM10 documentation, as well as the documentation for the SoftwareSerial library. As far as I could tell, nothing was explicitly wrong. Furthermore, most HM10 articles I found used it with connected to an Android, not a web app. So I’m really running out of ideas here. Any clues on why this doesn’t work?

Blazor ContentEditable data binding

I know that Blazor does not support data-binding for contenteditable div. What I have working is the following that allows text to be written and accessed through onInput.

<div role="textbox" contentEditable="true" @oninput="(e) => HandleInput(e, item.TODO_ID)">@item.TODO_TEXT</div>

The issue is I can’t figure out how to update TODO_TEXT with this new text. Anyone has any workarounds to suggest? Even recommendations for other controls that would support markup text.

Note: The above uses JSInterop code from here to ensure that any edits are passed along through oninput:

document.addEventListener("input", onInput);
function onInput(e) {
 let target = e.target;
 if (target.localName == "div") {
   if (!target.value && !target.__contenteditable) target.__contenteditable = true;
   if (target.__contenteditable) target.value = target.innerText;
 }
}

how to use createBrowserRouter in react + react router dom?

In my application I am using BrowserRouter component to render my routes or components . But I want to use loader functionality. but my current approach I am not able to use that feature.

 <BrowserRouter>
      <AppRoutes />
    </BrowserRouter>

As suggested by below link I need to use createBrowserRouter function .
why loader function not called in react js?
https://reactrouter.com/en/main/routers/picking-a-router

current way of routing.

export default function AppRoutes() {
  return (
    <Layout>
      <Routes>
        <Route element={<RequireAuth />}>
          <Route
            path={'/'}
            element={
              <React.Suspense
                fallback={<div>loading</div>}
                children={<Booking />}
              />
            }
          ></Route>
        </Route>
        <Route element={<RequireAuth />}>
          <Route
            path={'/app'}
            element={
              <React.Suspense
                fallback={<div>loading</div>}
                children={<App />}
              />
            }
          ></Route>
        </Route>
      </Routes>
    </Layout>
  );
}

now I am trying to refactor my routing using createBrowserRouter .. I tried like this

const router = createBrowserRouter([
  {
    path: '/',
    loader: () => {
      console.log('0000');
      return 'ss';
    },
    element: <RequireAuth />,
  },
  {
    path: '/app',
    loader: () => {
      console.log('0000');
      return 'ss';
    },
    element: <RequireAuth />,
  },
]);

how to render component (Booking and App component). how I will render children in createBrowserRouter approach .any idea ??

here is my code
https://stackblitz.com/edit/vitejs-vite-6gg4ab?file=src%2FApp.tsx,src%2Fmain.tsx,src%2Findex.css,src%2Froutes.tsx,src%2Flayout.tsx,src%2FRequireAuth.tsx,src%2Fbrowser-routes.tsx&terminal=dev

How to re render cards in a swiper using react-native-deck-swiper

I’m facing an issue with updating the content of cards in a swiper using react-native-deck-swiper. I have a button external to the swiper, and when pressing it I want to update the content of the current card and trigger a re-render to reflect the changes.

I’ve managed to update the state of the item correctly, but the card doesn’t re-render immediately. It only renders again when I start swiping the item.

The documentation suggests a possible fix, stating, “A possible fix for the situation is setting the cardIndex on the parent component whenever deck re-renders are needed.” However, my attempt to implement this hasn’t been successful.

I have noticed that the change is render when the overlay condition are required (even if no overlay is set).

Below is a reproducible example of the problem :

import React, { useRef, useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import Swiper from 'react-native-deck-swiper';

const cards = [
    { color: 'red', updated: false },
    { color: 'blue', updated: false },
    { color: 'green', updated: false },
    { color: 'yellow', updated: false },
    { color: 'purple', updated: false },
];

export default function App() {
    const [cardIndex, setCardIndex] = useState(0);
    const swiperRef = useRef(null);

    const updateCard = () => {
        cards[cardIndex].updated = !cards[cardIndex].updated;
        // Force re-render??
        setCardIndex(cardIndex); 
    };

    const onSwiped = () => {
        setCardIndex((cardIndex + 1) % cards.length); 
    };

    const renderCard = (card) => (
        <View style={[styles.card, { backgroundColor: card.color }]}>
            {card.updated && <Text style={styles.updatedText}>UPDATED</Text>}
        </View>
    );

    return (
        <View style={styles.container}>
            <Swiper
                ref={swiperRef}
                cards={cards}
                renderCard={renderCard}
                onSwiped={onSwiped}
                onSwipedLeft={onSwiped}
                onSwipedRight={onSwiped}
                cardIndex={cardIndex}
                infinite
            />
            <TouchableOpacity style={styles.button} onPress={updateCard}>
                <Text style={styles.buttonText}>Update card</Text>
            </TouchableOpacity>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f7f7f7',
        alignItems: 'center',
        justifyContent: 'center',
    },
    card: {
        width: '80%',
        height: '80%',
        justifyContent: 'center',
        alignItems: 'center',
        alignSelf: 'center',
      },
    updatedText: {
        position: 'absolute',
        fontSize: 24,
        fontWeight: 'bold',
        color: 'black',
    },
    button: {
        position: 'absolute',
        bottom: 20,
        padding: 10,
        backgroundColor: 'blue',
        borderRadius: 5,
    },
    buttonText: {
        color: 'white',
        fontSize: 16,
    },
});

I’d appreciate any insights on how to solve this issue and get the card to re-render immediately upon pressing the button. Thank you!

How to loop through a nested object and delete objects where values of keys match

How do I loop through a nested object of the form

{
  'AAA': 
   { oldName: { index: 0, first: 'Bob', last: 'Hanson' },
     newName: { index: 0, first: 'Bob', last: 'Hanson' }
   }, 
  'BBB': 
   { oldName: { index: 1, first: 'Velma', last: 'Jones' },
     newName: { index: 2, first: 'Velma', last: 'Roberts'} 
   },
  'CCC': 
   { oldName: { index: 2, first: 'Jou', last: 'Xi' },
     newName: { index: 3, first: 'Jou', last: 'Xi' } 
   },
  'DDD': 
   { oldName: { index: 3, first: 'Betty', last: 'Ford' },
     newName: undefined},
  'EEE': 
   { oldName: undefined,
     newName: { index: 1, first: 'Fred', last: 'Tree' } 
  } 
}

and delete all the nested objects where for each first level key AAA, BBB, CCC, DDD, EEE
the value of the key oldName = the value of key newName

So, I end up with

{
 'BBB': 
   { oldName: { index: 1, first: 'Velma', last: 'Jones' },
     newName: { index: 2, first: 'Velma', last: 'Roberts' } 
   },
  'DDD': 
   { oldName: { index: 3, first: 'Betty', last: 'Ford' },
     newName: undefined },
  'EEE': 
   { oldName: undefined,
     newName: { index: 1, first: 'Fred', last: 'Tree' } 
   } 
}

How can I limit the rows in tanstack table?

How can I limit the rows being shown in my tanstack query table? It has a default value of 10, is it possible to limit it for only 5? What I accomplish it, I make the selected values limit to [5,10,20,30,40,], but it didn’t change the default value of rows.

admin-data-table.tsx

 <div className="rounded-md border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => {
                  return (
                    <TableHead key={header.id}>
                      {header.isPlaceholder
                        ? null
                        : flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                    </TableHead>
                  );
                })}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() && "selected"}
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="h-24 text-center"
                >
                  No results.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>

        <div className="flex items-center justify-end space-x-2 py-4">
          <DataTablePagination table={table} />
        </div>
      </div>

admin-data-table-pagination.tsx

import {
    ChevronLeftIcon,
    ChevronRightIcon,
    DoubleArrowLeftIcon,
    DoubleArrowRightIcon,
  } from "@radix-ui/react-icons"
  import { Table } from "@tanstack/react-table"
  
  import { Button } from "@/components/ui/button"
  import {
    
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
  } from "@/components/ui/select"
  
  interface DataTablePaginationProps<TData> {
    table: Table<TData>
  }
  
  export function DataTablePagination<TData>({
    table,
  }: DataTablePaginationProps<TData>) {
    return (
      <div className="flex items-center justify-between px-2">
        <div className="flex-1 text-sm text-muted-foreground">
          {table.getFilteredSelectedRowModel().rows.length} of{" "}
          {table.getFilteredRowModel().rows.length} row(s) selected.
        </div>
        <div className="flex items-center space-x-6 lg:space-x-8">
          <div className="flex items-center space-x-2">
            <p className="text-sm font-medium">Rows per page</p>
            <Select
              value={`${table.getState().pagination.pageSize}`}
              onValueChange={(value) => {
                table.setPageSize(Number(value))
              }}
            >
              <SelectTrigger className="h-8 w-[70px]">
                <SelectValue placeholder={table.getState().pagination.pageSize} />
              </SelectTrigger>
              <SelectContent side="top">
                {[5, 10, 20, 30, 40].map((pageSize) => (
                  <SelectItem key={pageSize} value={`${pageSize}`}>
                    {pageSize}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex w-[100px] items-center justify-center text-sm font-medium">
            Page {table.getState().pagination.pageIndex + 1} of{" "}
            {table.getPageCount()}
          </div>
          <div className="flex items-center space-x-2">
            <Button
              variant="outline"
              className="hidden h-8 w-8 p-0 lg:flex"
              onClick={() => table.setPageIndex(0)}
              disabled={!table.getCanPreviousPage()}
            >
              <span className="sr-only">Go to first page</span>
              <DoubleArrowLeftIcon className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              className="h-8 w-8 p-0"
              onClick={() => table.previousPage()}
              disabled={!table.getCanPreviousPage()}
            >
              <span className="sr-only">Go to previous page</span>
              <ChevronLeftIcon className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              className="h-8 w-8 p-0"
              onClick={() => table.nextPage()}
              disabled={!table.getCanNextPage()}
            >
              <span className="sr-only">Go to next page</span>
              <ChevronRightIcon className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              className="hidden h-8 w-8 p-0 lg:flex"
              onClick={() => table.setPageIndex(table.getPageCount() - 1)}
              disabled={!table.getCanNextPage()}
            >
              <span className="sr-only">Go to last page</span>
              <DoubleArrowRightIcon className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>
    )
  }
  

React Hook Form’s isDirty returns false, but dirtyFields returns a dirty field

I’m checking React Hook Form’s isDirty when clicking outside of a modal:

const formSchema = z.object({
  name: z.string().min(1, 'Name is required'),
});

export default function AssetAddModal({
  isOpen,
  setIsOpen,
}: AssetAddModalProps) {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: '',
    },
  });
}
function handleCloseModal() {
  const { isDirty, dirtyFields, touchedFields } = form.formState;
  console.log('isDirty:', isDirty);
  console.log('dirtyFields:', dirtyFields);
  console.log('form.control._getDirty:', form.control._getDirty());

}

This is what is logged when you type in the form and click outside (first time):

isDirty: false

dirtyFields: {
  name: true
}

form.control._getDirty: true

This is what is logged when you repeat the proccess a second time:

isDirty: true

dirtyFields: {
  name: true
}

form.control._getDirty: true

Why isn’t isDirty being set to true the first time?

Note: this is the whole component.

Caesars Cipher with a twist: how to remove random letters from a string

I am working on a variation of Caesar’s Cipher in JavaScript. The variation is that a random letter is generated and inserted every 2 spaces. I have the encryption working just fine. I have the decryption mostly working. My program decrypts it, but I do not know how to remove the random letters. I am writing a function to remove the letters, my current code for that is as follows:

let decryptedMessage = seoekx tbhea mtidrniughkt

function finalMessage (decryptedMessage) {
    let finalMessage = "";
    for (let i = 1; i < decryptedMessage.length - 1; i++) {
        if (i % 2 === 0) {
            finalMessage += decryptedMessage.replace(decryptedMessage[i],"");
        }
        else {
            finalMessage += decryptedMessage[i];
        }
    }
    return finalMessage;
}

const finalMessageResult = finalMessage(decryptedMessageResult);
console.log(`The final decrypted message is ${finalMessageResult}`);

This is my Output:

eseekx tbhea mtidrniughkteseoex tbhea mtidrniughktxseoekxtbhea mtidrniughkttseoekx thea mtidrniughkthsoekx tbhea mtidrniughktaseoekxtbhea mtidrniughktmseoekx bhea mtidrniughktiseoekx tbhea mtirniughktrseoekx tbhea mtidriughktiseoekx tbhea mtidrnighktgseoekx tbea mtidrniughktk

I am thinking I need to pull the finalMessage out of the for loop, but I don’t know how to do that because I feel the if statement needs to be in the for loop to loop through the message.

Any help would be appreciated.

I feel I need to have it in a for loop with an if else statement. The logic in my head is to use i % 2 === 0, then to replace that element with “”. But clearly what I have in my head and what is being executed are not the same. I am expecting to have the code remove the random letters from the string, creating a readable message.

How can I make a toggle button in AppGyver (SAP Build Apps)

I’m trying to make an onboarding experience in an app I’m designing (using AppGyver) where the user may select multiple tags for themselves. While I can use a simple checkbox, I would like to instead use toggleable buttons that change color/visual state when selected, but I’m not sure how to do this. I am unable to find any variables or formulas where I can change the style of a button after it is tapped in the logic.

For reference, here is what the buttons look like when they are not toggled/unselected.
Non-toggled/selected buttons

Ideally, the rounded buttons with content in them would change to a blue background with white text after being selected. Could someone please tell me the proper logic flow I need to accomplish this?

I have tried looking into the theme/smart color system in AppGyver, but I can’t seem to find any changeable variables that affect the style of the button component itself. I have also tried to use the JavaScript flow component in AppGyver, but again, was unable to find anything useful there.

Jest testing keeps running forever

I have created a small jest test, and it seems like running forever:

export default class Core {
    app: any;
    port: string | undefined;

    constructor() {
        this.port = process.env.server_port;
        this.app = express();
        this.app.use(bodyParser.urlencoded({ extended: false }))
    }

    dispatch() {
        this.app.use((req: Request, res: Response, next: NextFunction) => {
            return routes(req, res, next);
        })

        const server = this.app.listen(this.port, () => {
            console.log('server is running')
        })

        server.close();
    }

    returnInstance() {
        return this.app;
    }
}

const core = new Core();
core.dispatch();


const app = core.returnInstance();

const payloadCorrectLoginCredentials = {
    email: '[email protected]',
    password: '1234'
};



    describe('Customer api', () => {
        test('[POST] /login, with correct credentials', async () => {
            const response = await request(app)
                .post('/api/customer/login')
                .set('Content-Type', 'application/x-www-form-urlencoded')
                .send(payloadCorrectLoginCredentials)
    
            expect(response.statusCode).toBe(200);
    
        });
    });

I have tried to actually closing the server when the jest call is done, then again, how to mark it done() in async?