typeScript with next.js Slider doesn’t work

SaleSlider.tsx

import React, { useState } from "react";
import { SaleSliderItem } from "@/components/SaleSliderItem/SaleSliderItem";
import styles from "./SaleSlider.module.scss";
export function SaleSlider({ response }: { response: any }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const handleForward = () => {
    if (currentIndex < response.sliderSaleList.length - 1) {
      setCurrentIndex(currentIndex + 1);
    } else {
      setCurrentIndex(0);
    }
  };
  const handleBackward = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    } else {
      setCurrentIndex(response.sliderSaleList.length - 1);
    }
  };
   if (
    Array.isArray(response.sliderSaleList) &&
    response.sliderSaleList.length > 0
  ) {
    return (
      <>
        <div className={styles.sliderContainer}>
          <button className={styles.sliderBtn} onClick={handleBackward}>
            backward
          </button>
          <div className={styles.flexContainerPrimary}>
            {response.sliderSaleList.map((item: any, idx: any) => (
              <SaleSliderItem
                item={item}
            isVisible={idx === currentIndex}
            key={idx}
            currentIndex={currentIndex}
          />
        ))}
      </div>

      <button className={styles.sliderBtn} onClick={handleForward}>
        forward
      </button>
    </div>
  </>
);
  } else {
    return <div>Keine Produkte verfügbar</div>;
  }
}

SaleSliderItem.tsx

import React from "react";
import styles from "./SaleSliderItem.module.scss";

export function SaleSliderItem({
  item,
  isVisible,
  currentIndex,
}: {
  item: any;
  isVisible: boolean;
  currentIndex: number;
}) {
  return (
    <div
      className={styles.flexContainerSecondary}
      style={{ display: isVisible ? "flex" : "none" }}>
      {item.stageProductImage &&
        item.stageProductImage.data &&
        item.stageProductImage.data.attributes && (
          <img
            src={`${process.env.STRAPI_URL as string}${
              item.stageProductImage.data.attributes.formats.small.url
            }`}
            alt={item.stageProductImage.data.attributes.alternativeText}
          />
        )}
      <div className={styles.flexContainerTertiary}>
        {item.stageBestseller ? (
          <p className={styles.bestseller}>Bestseller</p>
        ) : null}
        <h1>{item.stageProductName}</h1>
        <h3>€ {item.stageDiscountPrice}</h3>
        <p>
          {item.stageDiscountStartDate} ~ {item.stageDiscountEndDate}
        </p>
        <div>
          <button>ADD TO CART</button>
          <button>❤️</button>
        </div>
        <button>FIND SIMILAR STYLES</button>
      </div>
    </div>
  );
}

JSON For convenience, the “id” of each “sliderSaleList” is repeated in the same format from 1 to 7.

{
  "data": {
    "id": 1,
    "attributes": {
      "createdAt": "2023-06-05T09:13:51.046Z",
      "updatedAt": "2023-09-25T08:46:55.018Z",
      "publishedAt": "2023-09-21T11:10:34.193Z",
      "slug": "homepage",
      "stageBrand": "SALE",
      "sliderSaleList": [
        {
          "id": 1,
          "stageDiscountStartDate": "2023-09-20T22:00:00.000Z",
          "stageDiscountEndDate": "2023-09-27T22:00:00.000Z",
          "stageBestseller": true,
          "stageDiscountPrice": 28.99,
          "stageProductName": "BROWN SNEAKERS",
          "stageProductImage": {
            "data": {
              "id": 3,
              "attributes": {
                "name": "brown_sneakers.png",
                "alternativeText": "brown_sneakers",
                "caption": null,
                "width": 693,
                "height": 672,
                "formats": {
                  "small": {
                    "ext": ".png",
                    "url": "/uploads/small_brown_sneakers_f99b1f226c.png",
                    "hash": "small_brown_sneakers_f99b1f226c",
                    "mime": "image/png",
                    "name": "small_brown_sneakers.png",
                    "path": null,
                    "size": 135.01,
                    "width": 500,
                    "height": 485
                  },
                },
                "hash": "brown_sneakers_f99b1f226c",
                "ext": ".png",
                "mime": "image/png",
                "size": 58.09,
                "url": "/uploads/brown_sneakers_f99b1f226c.png",
                "previewUrl": null,
                "provider": "local",
                "provider_metadata": null,
                "createdAt": "2023-09-21T15:55:42.086Z",
                "updatedAt": "2023-09-21T15:55:42.086Z"
              }
            }
          }
        },
        {
          "id": 7,
          "stageDiscountStartDate": "2023-08-31T22:00:00.000Z",
          "stageDiscountEndDate": "2023-09-25T22:00:00.000Z",
          "stageBestseller": true,
          "stageDiscountPrice": 58.99,
          "stageProductName": "CARGO TROUSERS",
          "stageProductImage": {
            "data": {
              "id": 9,
              "attributes": {
                "name": "cargo_trousers.png",
                "alternativeText": "cargo_trousers",
                "caption": null,
                "width": 598,
                "height": 826,
                "formats": {
                  "small": {
                    "ext": ".png",
                    "url": "/uploads/small_cargo_trousers_9d9cc4cc95.png",
                    "hash": "small_cargo_trousers_9d9cc4cc95",
                    "mime": "image/png",
                    "name": "small_cargo_trousers.png",
                    "path": null,
                    "size": 125.86,
                    "width": 362,
                    "height": 500
                  },
                },
                "hash": "cargo_trousers_9d9cc4cc95",
                "ext": ".png",
                "mime": "image/png",
                "size": 68.64,
                "url": "/uploads/cargo_trousers_9d9cc4cc95.png",
                "previewUrl": null,
                "provider": "local",
                "provider_metadata": null,
                "createdAt": "2023-09-24T20:38:35.849Z",
                "updatedAt": "2023-09-24T22:34:04.160Z"
              }
            }
          }
        }
      ]
    }
  },
  "meta": {
  }
}

**I’m trying to create a slider with strapi. I want to write the slider logic separately from the slider item component. The forward and back buttons don’t work, obviously the console shows that the picture is mapped, but the next button doesn’t work.

FYI: (I also have this Warning in my Browser)

Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>.

Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.

Can anyone help me with this?
I would really appreciate it:)!

I fetched my strapi address to page.tsx and I’m attaching JSON String here.**

JavaScript Not Executing on Initial Template Rendering

I’m experiencing a problem where JavaScript isn’t functioning as expected during the initial rendering of my web template (haml). Although I’ve included JavaScript code, it doesn’t run on the initial page load. Interestingly, even a basic console.log statement doesn’t appear in the console until I refresh the page.

this is what my template looks like

- if user.present?
  %div#button-container
    %a#my-test.button{'data-user-id' => user.id, :href => '#'}
      = image_tag('https://test.button.svg', id: 'Button', style: 'padding-top: 20px;')

:javascript
  console.log('Inside Javascript')
  $(document).ready(function() {
    console.log('Inside document.ready()')
  });

I’m finding it difficult to understand what the issue could be here. Neither console logs anything during the initial template rendering, but upon reloading the page, they log messages, indicating that the JavaScript is now functioning correctly.

How to sum values of JSON objects of similar id?

I’m trying to sum values of JOSN array objects that have the same id.

for example JSON array one is:

[{
    "id": 1,
    "value": 3
},

{
    "id": 2,
    "value": 5
},
{
    "id": 3,
    "value": 2
}]

and JSON array two is:

[{
    "id": 1,
    "value": 2
},

{
    "id": 2,
    "value": 3
},
{
    "id": 4,
    "value": 2
}]

I want to merge both JSON arrays while summing the values of similar objects (i.e. those of similar id).

Final result I want is as follows:

[{
    "id": 1,
    "value": 5
},
{
    "id": 2,
    "value": 8
},
{
    "id": 3,
    "value": 2
},
{
    "id": 4,
    "value": 2
}]

Any help would be appreciated as I’m stuck right now..
Thanks

AWS Rekognition Client – Compare Faces

I’m trying to use AWS Rekognition Client (SDK) in Javascript. I want to compared two faces using JPEG images sending the following request:

{SimilarityThreshold: 70, SourceImage: {,…}, TargetImage: {,…}}
SimilarityThreshold: 70,
SourceImage: {
Bytes: “dataimage/jpegbase64/9j/4AAQSkZJRgABAQAAAQABAAD/4
},
TargetImage: {
Bytes: “dataimage/jpegbase64/9j/4AAQSkZJRgABAQAAAQABAAD/2
}

Each Image I send as Uint8Array after check the type on github but I received the following error:

InvalidImageFormatException: Request has invalid image format
at de_InvalidImageFormatExceptionRes (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/client-rekognition/dist-es/protocols/Aws_json1_1.js:4384:23)
at de_CompareFacesCommandError (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/client-rekognition/dist-es/protocols/Aws_json1_1.js:679:25)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js:8:24)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/middleware-signing/dist-es/awsAuthMiddleware.js:20:20)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js:36:46)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js:9:26)
at async magia (webpack-internal:///(app-pages-browser)/./app/page.js:91:30)

Is the correct format Uint8Array? I tested using base64 and I got the same error.

I will appreciate your feedback

Why my data is not updating when i use useContext

this some react components from my code
i want to pass an array called orderedMeals from the Meals component to the CartList component

Meals component

return (
    <CartContext.Provider value={{ array: orderedMeals }}>
      <ul>
        {DUMMY_MEALS.map((meal) => (
          <Meal
            key={meal.id}
            title={meal.name}
            description={meal.description}
            price={meal.price}
            id={meal.id}
            addToOrderedMeals={addToOrderedMeals}
          />
        ))}
      </ul>
    </CartContext.Provider>
  );

CartList component

import React, { useContext } from "react";
import classes from "./CartList.module.css";
import CartContext from "../Context/Context";

const CartList = (props) => {
  const { array } = useContext(CartContext); 

  console.log("Array from context:", array);
  return (
    <>
      <div className={classes.backdrop} />
      <div className={classes.modal}>
        <div className={classes.meals}>
          {array.map((element) => {
            console.log(element);
            return <div key={element.id}>{element.title}</div>;
          })}
        </div>
        <div className={classes.amount}>
          <h3>Amount</h3>
          <h3>$22</h3>
        </div>
        <span className={classes.actions}>
          <button className={classes.button}>Confirm</button>
          <button onClick={props.onClick} className={classes.button}>
            Return
          </button>
        </span>
      </div>
    </>
  );
};

export default CartList;

and this is the CartContext component

import { createContext } from "react";

const CartContext = createContext({
  array: [],
  amount: 4,
});
console.log(CartContext);

export default CartContext;

i am trying to pass some data from a component to another using useContext, but the data that i recive doesn’t update, i always receive an empty array.

Hello Everyone. Just wanna apologize in advance for asking a redundant question but I’m having a specific problem in regards to creating with JS [closed]

I am a self-taught individual who has just finished a UDEMY course on JS.
Half way through the course, the guy was going way too fast for me and everything started to turn gibberish.

Though I did strengthen some fundamentals of JS by watching videos and following along with side projects, I am still having alot of trouble remembering syntax and exactly HOW to start coding when I want to build something.

When I watch other tutorials, people know exactly what they need next in order to make the feature of that code. What i was taught in the tutorial is sometimes worlds apart from when I watch someone build something.

I see something like this by itself with no value assigned to it (var index = ” “)

And then this person uses this empty index variable in the code below and I am completely lost.

My questions is –> How do I start to independently code and actually mentally work through what i need?

Much love and thanks for answers.

Some quick bullet points:

  • Tried watching more videos and following along
  • Started to piece things together but i’m still having trouble coding independently
  • Looked different examples of JS projects being made with basic 4-5 line code logic and I understand every bit of it but I just can’t do it myself out of sheer memory

jQuery – element.find only returns the first result in a list. It doesn’t return the value I clicked on

Im writing some tracking in GTM and the script is only returning the first value in a list regardless of which ‘brand’ is clicked on.

How would I update the brandImage variable to ‘find’ the element I clicked on rather than only the first in the below HTML?

Thanks

<script>
    if (jQuery({{Click Element}}).closest('.c-category-menu__submenu').length > 0) { 
      subMenu = jQuery({{Click Element}}).closest('.c-category-menu__submenu').attr('aria-label');

      var submenuElement = jQuery({{Click Element}}).closest('.c-category-menu__submenu');
      var brandImage = submenuElement.find('.c-category-menu__item__brand__image');
      if (brandImage.length > 0) {
         subMenu = ' brand | ' + submenuElement +  brandImage.attr('alt');
      } 
    }
</script>




<html>
<ul class="c-category-menu__submenu" aria-label="shop-by-brand">
    <li class="c-category-menu__item c-category-menu__item--brand">
        <div class="sub-brand-container">
            <div class="sub-brand-interior">
                <a href="/brand/brand1" class="c-category-menu__item__brand__link">
                    <img class="c-category-menu__item__brand__image" src="" alt="brand1">
                </a>
            </div>
            <div class="sub-brand-interior">
                <a href="/brand/brand2" class="c-category-menu__item__brand__link">
                    <img class="c-category-menu__item__brand__image" src="" alt="Brand2">
                </a>
            </div>
            <div class="sub-brand-interior">
                <a href="/brand/brand3" class="c-category-menu__item__brand__link">
                    <img class="c-category-menu__item__brand__image" src="" alt="Brand3">
                </a>
            </div>
            <div class="sub-brand-interior">
                <a href="/brand/brand4" class="c-category-menu__item__brand__link">
                    <img class="c-category-menu__item__brand__image" src="" alt="Brand4">
                </a>
            </div>
            <div class="sub-brand-interior">
                <a href="/brand/brand5" class="c-category-menu__item__brand__link">
                    <img class="c-category-menu__item__brand__image" src="" alt="Brand5">
                </a>
            </div>
            <div class="sub-brand-interior">
                <a href="/brand/brand6" class="c-category-menu__item__brand__link">
                    <img class="c-category-menu__item__brand__image" src="" alt="Brand6">
                </a>
            </div>
        </div>
    </li>
</ul>

</html>

I ran the JS and it is always printing ‘brand1’ regardless of whichever I click on.

sum the value inside array of objects based on multiple conditions

I have this object

[
      {
            "year": 2020,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2020,
            "term": 2,
            "worthAmountEGP": 300000
      },
      {
            "year": 2021,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2021,
            "term": 2,
            "worthAmountEGP": 1000000
      },
      {
            "year": 2021,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2021,
            "term": 2,
            "worthAmountEGP": 400000
      },
      {
            "year": 2022,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2022,
            "term": 2,
            "worthAmountEGP": 1000000
      }
]

I have been trying to sum the worthAmountEGP based on multiple conditions (same year and same term )

this is what I have been trying

const transformed = Object.values(
      aa.reduce((acc, { term, worthAmountEGP, year }) => {
            acc[term] = acc[term] || { term, worthAmountEGP: 0 };
            acc[term].worthAmountEGP += worthAmountEGP;
            return acc;
      }, {})
);

this is my output

Transformed: [
  { term: 1, worthAmountEGP: 5000000 },
  { term: 2, worthAmountEGP: 3200000 },
]

my desired output is

[
  { term: 1, worthAmountEGP: 0, year:2020 },
  { term: 2, worthAmountEGP: 300000, year:2020 },
  { term: 1, worthAmountEGP: 0, year:2021},
  { term: 2, worthAmountEGP: 1400000, year:2021},
  { term: 1, worthAmountEGP: 0, year:2022},
  { term: 2, worthAmountEGP: 1000000, year:2022},
]

Visual Studio Code .class [closed]

I’m just starting with visual studio code, and I’m trying to edit a JavaScript .class file. However, it keeps saying I can’t edit in read-only mode even though the file and folder it’s in are marked as not read-only. This file is from a decompiled mod file (which was given permission to edit source code). Thank you for looking at my question.

Tried marking file and folder as not read-only, tried doing the code-runner “run in terminal option”, checked for any options to edit this and coming up with nothing.

Typescript: How to satisfy union type with function and arguments

The union of (arg: string) => void and (arg: number) => void is (arg: never) => void, because no value can be a string and a number at the same time. But how can I work arround this issue in the following example?

type Test<T, U> =
  | {
      func: (arg: T) => void;
      data: T;
    }
  | {
      func: (arg: U) => void;
      data: U;
    };

function test<T, U>(x: Test<T, U>) {
  x.func(x.data);
}

In this example, x.data should always be of the correct type to sastisfy the function argument, but typescript can’t see it and errors with Argument of type 'string | number' is not assignable to parameter of type 'never'.

How do I ensure both my objects have loaded before I render the page?

I have a react app using firebase as my database. I am trying to load 2 separate objects and display their info on the page, problem is that only the “user” loads and is shown, but if I reload the page, the rest shows up so its loading but not on the initial rendering. Is there a way to make it work without manually reloading the page?

The code I currently have for the render is this one:
const [ dadosCarregados, setDadosCarregados ] = useState(false);
const { retrieveUser, getUserSheets, user, list } = useRetrieveDatabase()

useEffect(() => {
retrieveUser(userId).then(
getUserSheets(userId).then(
setDadosCarregados(true)
)
)
}, [dadosCarregados])

if(!user) {
return

Carregando…

}

return (//the loaded page)

the hooks that get the data are the following:
const retrieveUser = async (userId) => {
checkIfIsCancelled()
setLoading(true)

    try {
        const userDocRef = doc(collection(db, 'usuarios'), userId)
        const userDocSnapshot = await getDoc(userDocRef)

        if (userDocSnapshot.exists()) {
            setUser(userDocSnapshot.data())
        } else {
            console.log('Usuario não encontrado')
        }
    
    } catch (error) {
        console.log('Erro ao buscar usuário: ' + error)
    } finally {
        setLoading(false)
    }
}

const getUserSheets = async (userId) => {
    checkIfIsCancelled()
    setLoading(true)

    try {
        const sheetsQuery = query(collection(db, 'fichas'), where('Idcriador', '==', userId));
        const sheetsQuerySnapshot = await getDocs(sheetsQuery);

        const userSheets = sheetsQuerySnapshot.docs.map((doc) => doc.data());
        setList(userSheets);
    
    } catch (error) {
        console.log('Erro: ' + error)
        return []
    } finally {
        setLoading(false)
    }
}

I’ve tried making the two functions one, but it didn’t work. I also tried putting “dadosCarregados” and “list” on the if, but it ended up in an error. What else could I do?

WebSocket with Django and Expo not working

I am building an expo app that uses Django for backend. For the app I need to use WebSocket. But when I try to connect to the WebSocket on my Django project, I get

Not Found: /ws/
[25/Sep/2023 19:34:58] "GET /ws/ HTTP/1.1" 404 2678

This is my Expo code:

const socket = React.useRef(new WebSocket('ws://myIP:8000/ws/')).current;
    console.log(socket) 
    if (socket) {
        // Now you can safely work with the WebSocket object 
      } else {
        console.error('WebSocket is undefined.');
    }
    socket.onmessage = (event) => {
        console.log(event.data)
        // Handle incoming messages from the WebSocket server
      };
        
      socket.onopen = () => {
        // WebSocket connection opened 
        console.log("opened")
      };
      
      socket.onclose = (event) => {
        // WebSocket connection closed
      };
      
      socket.onerror = (error) => {
        // Handle WebSocket errors
        console.log("error")
      };

This is my Django code:

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
    'channels',
]

ASGI_APPLICATION = 'API.routing.application'

routing.py


from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from .consumers import YourWebSocketConsumer
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "API.settings")

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(
        [
            path("ws/", YourWebSocketConsumer.as_asgi()),
            # Add more WebSocket consumers and paths as needed
        ]
    ),
})

consumers.py


from channels.generic.websocket import AsyncWebsocketConsumer
import json

class YourWebSocketConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        data = json.loads(text_data)
        message = data['message']

        # Process the received message
        # You can send a response back to the client using self.send()

        await self.send(text_data=json.dumps({'message': 'Response to your message'}))

Implementing WebSocket is essential for my application’s functionality. How can I fix this so I could make the WebSocket work?

How to use DetectOverflow or Custom Middleware from Floating UI JS with Serverless Vanilla JS?

I am dealing with an overflow problem on my div when dragging my Floating UI tooltips. Floating UI has a solution for this natively called detectOverflow, but I’ve had issues trying to prevent it from erroring out. I believe I am having issues with using Custom Middleware with Floating UI as a whole.

I’ve got a .NET project where I am using Floating UI JS to show tooltips on draggable tag elements. They display information regarding my element types. The draggable are floating on top of a element where they are contained in. Importing Floating UI the traditional way has not worked for me. Even when setting the <src type=”module> (this has given me different complications with my code as well). So, I import from the FLoating UI CDN in my index.cshtml file the traditional Vanilla JS way:

<script src='https://cdn.jsdelivr.net/npm/@Html.Raw("@")floating-ui/[email protected]'></script>
<script src='https://cdn.jsdelivr.net/npm/@Html.Raw("@")floating-ui/[email protected]'></script>

In Script.js, a different file in the directory I utilize computePosition from Floating UI.js:

FloatingUIDOM.computePosition(draggableElement, tooltipElement, {
    placement: placement,
    middleware: [
        FloatingUICore.offset(5),
        FloatingUICore.flip(),
        FloatingUICore.shift({ padding: 5 }),
        FloatingUICore.arrow({ element: arrowElement }),
    ],
}).then(({ x, y, placement, middlewareData }) => {

    Object.assign(tooltipElement.style, {
        left: `${x}px`,
        top: `${y}px`,
    });

    // Accessing the data
    const { x: arrowX, y: arrowY } = middlewareData.arrow;

    const staticSide = {
        top: 'bottom',
        right: 'left',
        bottom: 'top',
        left: 'right',
    }[placement.split('-')[0]];

    Object.assign(arrowElement.style, {
        left: arrowX != null ? `${arrowX}px` : '',
        top: arrowY != null ? `${arrowY}px` : '',
        right: '',
        bottom: '',
        [staticSide]: '-4px',
    });
});

This works great for me and correctly places the tooltips with its respective draggableElement.
Notice that in order for me to use ComputePosition properly I had to prefix with FloatingUIDom. in order to avoid console errors. However, when I try to use detectOverflow like so,

const detectLabelOverflow = {
    name: 'detectLabelOverflow',
    async fn(state) {
      const overflow = await FloatingUIDOM.detectOverflow(state, {
        boundary: document.querySelector("#panzoomRect")
        //boundary: document.querySelector('#partialDiv')
      });
      return {};
    },
  };


FloatingUIDOM.computePosition(draggableElement, tooltipElement, {
    placement: placement,
    middleware: [
        FloatingUICore.offset(5),
        FloatingUICore.flip(),
        FloatingUICore.shift({ padding: 5 }),
        FloatingUICore.arrow({ element: arrowElement }),
        [detectLabelOverflow]
    ],
}).then(({ x, y, placement, middlewareData }) => {

    Object.assign(tooltipElement.style, {
        left: `${x}px`,
        top: `${y}px`,
    });

    // Accessing the data
    const { x: arrowX, y: arrowY } = middlewareData.arrow;

    const staticSide = {
        top: 'bottom',
        right: 'left',
        bottom: 'top',
        left: 'right',
    }[placement.split('-')[0]];

    Object.assign(arrowElement.style, {
        left: arrowX != null ? `${arrowX}px` : '',
        top: arrowY != null ? `${arrowY}px` : '',
        right: '',
        bottom: '',
        [staticSide]: '-4px',
    });
});

I run into this error, without any extra info. I understand core is the one of the CDN import files that house FLoating UI:

[email protected]:1 Uncaught (in promise) TypeError: p is not a function
at t.computePosition ([email protected]:1:5480)

Clicking on that error reveals this, where the error is at line 16 , {x: h, y: y, data: x, reset: w} = await p({:

t.computePosition = async(t,e,n)=>{
        const {placement: i="bottom", strategy: o="absolute", middleware: r=[], platform: a} = n
          , l = r.filter(Boolean)
          , s = await (null == a.isRTL ? void 0 : a.isRTL(e));
        let f = await a.getElementRects({
            reference: t,
            floating: e,
            strategy: o
        })
          , {x: c, y: u} = b(f, i, s)
          , m = i
          , d = {}
          , g = 0;
        for (let n = 0; n < l.length; n++) {
            const {name: r, fn: p} = l[n]
              , {x: h, y: y, data: x, reset: w} = await p({
                x: c,
                y: u,
                initialPlacement: i,
                placement: m,
                strategy: o,
                middlewareData: d,
                rects: f,
                platform: a,
                elements: {
                    reference: t,
                    floating: e
                }
            });
            c = null != h ? h : c,
            u = null != y ? y : u,
            d = {
                ...d,
                [r]: {
                    ...d[r],
                    ...x
                }
            },
            w && g <= 50 && (g++,
            "object" == typeof w && (w.placement && (m = w.placement),
            w.rects && (f = !0 === w.rects ? await a.getElementRects({
                reference: t,
                floating: e,
                strategy: o
            }) : w.rects),
            ({x: c, y: u} = b(f, m, s))),
            n = -1)
        }
        return {
            x: c,
            y: u,
            placement: m,
            strategy: o,
            middlewareData: d
        }
    }

Lastly, I understood that detectOverflow was considered custom middleware and tried to see if I could just get that to function, but I would get the same error as well:

const shiftByOnePixel = {
  name: 'shiftByOnePixel',
  fn({x, y}) {
    return {
      x: x + 1,
      y: y + 1,
    };
  },
};

FloatingUIDOM.computePosition(draggableElement, tooltipElement, {
    placement: placement,
    middleware: [
        FloatingUICore.offset(5),
        FloatingUICore.flip(),
        FloatingUICore.shift({ padding: 5 }),
        FloatingUICore.arrow({ element: arrowElement }),
        [shiftByOnePixel]
    ],
}).then(({ x, y, placement, middlewareData }) => {

    Object.assign(tooltipElement.style, {
        left: `${x}px`,
        top: `${y}px`,
    });

    // Accessing the data
    const { x: arrowX, y: arrowY } = middlewareData.arrow;

    const staticSide = {
        top: 'bottom',
        right: 'left',
        bottom: 'top',
        left: 'right',
    }[placement.split('-')[0]];

    Object.assign(arrowElement.style, {
        left: arrowX != null ? `${arrowX}px` : '',
        top: arrowY != null ? `${arrowY}px` : '',
        right: '',
        bottom: '',
        [staticSide]: '-4px',
    });
});