Unknown Error: Warning: Attempted to synchronously unmount a root while React was already rendering

I created a generic Carousel, and one of the sub components causes errors when I test it with vitest and @testing-library/react

Here is my sub component that causes errors : (CarouselContent) :

const CarouselContent = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(({className, ...props}, ref) => {
    const {carouselRef, orientation} = useCarousel();

    return (
        <div ref={carouselRef} className='flex justify-center overflow-hidden'>
            <div
                ref={ref}
                className={clsx("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className)}
                {...props}
            />
        </div>
    );
});

Here is my test :

import {render, screen} from "@testing-library/react";
import {Carousel, CarouselContent, CarouselItem} from "ui/components/Carousel/Carousel";

it("renders Carousel component and navigates through items", () => {
    render(
        <Carousel>
            <CarouselContent>
                <CarouselItem>Item 1</CarouselItem>
                <CarouselItem>Item 2</CarouselItem>
                <CarouselItem>Item 3</CarouselItem>
            </CarouselContent>
        </Carousel>
    );

    [...]
});

If I remove <CarouselContent> it works. But of course, I need it later in my web pages.

Here is the errors I get :

 FAIL  src/__tests__/components/Carousel/Carousel.test.tsx > renders Carousel component and navigates through items
Unknown Error: Error: Uncaught [TypeError: undefined is not a function]


FAIL  src/__tests__/components/Carousel/Carousel.test.tsx > renders Carousel component and navigates through items
Unknown Error: Warning: Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition.%s

Vitest caught 2 unhandled errors during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.

Error: Should not already be working.

How can i create components and containers in App.js when tsparticles pacakage is installed?

I have started the app by using this “create-react-app your_app –template particles” and it works but when i created a components folder, which contains four different folders and four different files then it started giving me different bugs issues.This is the code have written that is not working. What am i writing wrongly in this code proffessional in the house help me out. Thanks

import React, { useEffect, useState } from "react";
import Particles, { initParticlesEngine } from "@tsparticles/react";
import { loadFull } from "tsparticles";
import Navigation from "./Components/Navigations/Navigation";
import Logo from "./Components/Logos/Logo.js";
import ImageLinkForm from "./Components/ImageLinkForm/ImageLinkForm";
import Rank from "./Components/Ranks/Rank";
import "./App.css";
import particlesConfig from "./particles.json";

function App() {
  const [init, setInit] = useState(false);

  useEffect(() => {
    if (!init) {
      initParticlesEngine(async (engine) => {
        await loadFull(engine);
      }).then(() => {
        setInit(true);
      });
    }
  }, [init]);

  return (
    <div className="App">
      {init && <Particles options={particlesConfig} />}
      {/* Your other components */}
      {<Navigation />}
      {<Logo />}
      {<Rank />}
      {<ImageLinkForm />}
    </div>`your text`
  );
}

export default App;

Display API response as a card in html

I am new to JavaScript and so I’m a bit confused here , I have an API response that looks like this

{

      "title": "Bari Bari Densetsu",

      "id": "bari-bari-densetsu",

      "episode": "2",

      "episode_id": "bari-bari-densetsu-episode-2",

      "subOrdub": "SUB",

      "image_url": "https://gogocdn.net/cover/bari-bari-densetsu.png"
}

And I want it in the form of a card in html how do I do it with JavaScript

object Object instead of JSON. Why?

So, i am trying to connect my Kotlin code and Node.js backend, trying to POST some JSON info, but have [object Object] as a req.body. Why so and how to fix this?

Main.kt:

import com.sun.net.httpserver.Request
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString

@Serializable
data class UsrData(val first_name: String, val username: String)


fun main() {
    val client = HttpClient.newBuilder().build();
    val requestBody = Json.encodeToString(UsrData("Alex", "ztrix"))
    println(requestBody.javaClass) // class java.lang.String
    val request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost:3000/niggawhat"))
        .POST(HttpRequest.BodyPublishers.ofString(requestBody))
        .build()
    val response = client.send(request, HttpResponse.BodyHandlers.ofString());
    println(response.body()) // Hello, [object Object]
}

index.js

const express = require("express")
const app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.json());

app.post("/niggawhat", function(req, res) { 
    console.log("Post request arrived with " + req.body)
    res.send("Hello, " + req.body)
  }); 

app.listen(3000, function(){ 
  console.log("server is running on port 3000")
})

I tried everything connected with app.use(bodyParser.json()), val jsonParser = bodyParser.json() and others. Nothing seems to work.

React JS – Handle loading states of two queries

In my home page, I have to load some posts and songs from the database. Currently, I initially set a loading state variable to true, and then inside a useEffect, perform a get request for the posts and songs, store them in state, and once they have been fetched and stored, then set loading to false. I would simply display a loading spinner if loading was true, else I would display and loop over posts and songs

However, I want to display the posts and songs as soon as they are available, therefore if the posts are loaded faster than the songs, I want to display the posts and then a loading spinner below the displayed posts, indicating the songs are still being loaded.

My current solution to this is to have two loading state variables for posts and songs, such as loadingPosts and loadingSongs, and then have the following conditions to check if they are loading:

loadingPosts && <Spinner /> : <div>  Map over and display posts </div>
loadingSongs && <Spinner /> : <div>  Map over and display songs</div>

However, I would like a cleaner and more concise method to handle this. After researching, I discovered react-query to potentially help with this issue. Could react-query be used to simplify this code? Also, are there any tradtional react methods to simplify this? Thanks.

how to divide exponential values in javascript [duplicate]

I want to divide the exponential values by 1000 in Javascript. For now I am using this calculation:

1.02e+30 / Math.pow(10, 3) 

In this case I am getting result as 1.0200000000000001e+27, but if I divide 1.03e+30 / Math.pow(10, 3) this value I am getting 1.03e+27 like this. Can anyone please explain why I am getting like this.

1.02e+30 / Math.pow(10, 3) ==> 1.0200000000000001e+27

1.03e+30 / Math.pow(10, 3) == > 1.03e+27

Rendering a new pug template fails in ExpressJS

I’m fairly new to ExpressJS and currently I’m making a sort of basic search engine and I have 2 pug template files called index.pug (the default search page) and search.pug (search results page) and an expressjs file called app.js that handles responses based on the request paths. The default page when a request is sent to the server is index.pug and this is what the server-side app.js contains:

var express = require('express');
var path = require('path');

const app = express();
const port = 3000;

//options
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, '/public/views'));

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
    res.render('index');
});

app.get('/searchpage', (req, res) => {
    console.log("RECEIVED searchpage")
    var key = req.query.keyword.toLowerCase();
    res.render('search', {keyword: key});
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`)
});

In my index.pug file, if a user presses “Enter”, the browser should render search.pug. Here’s my index.pug:

<!doctype html>
html
    head
        meta(charset="utf-8")
        meta(name="viewport" content="width=device-width, initial-scale=1.0")
        link(rel="stylesheet" href="../stylesheets/index_style.css")
    body
        div#content
            div#search_bar
                input(type="text" id="search" name="search_engine" placeholder="Enter Keyword Here" required)
        script(src="../javascripts/index.js")

Here is the index.js file that runs on the above page.

var search_bar = document.getElementById("search");

search_bar.addEventListener('keypress', getData);

async function getData(evt){
    if (evt.key == "Enter" && search_bar.checkValidity()){
        var search_keyword = search_bar.value;
        try {
            let response = await fetch('http://localhost:3000/searchpage?keyword='+search_keyword);
            if (response.status == 200){
                console.log("Changing Webpage...")   
            }
            else{
                console.log("HTTP return status: "+response.status);
            }
        }
        catch {
            console.log("Fetch Error!");
        }
    }
}

The problem here is that the after pressing enter, search.pug is not rendered.

Here is my simple search.pug:

<!doctype html>
html
    head
        meta(charset="utf-8")
        meta(name="viewport" content="width=device-width, initial-scale=1.0")
    body
        div#search_bar
            input(type="text" id="search" name="search_engine" placeholder="Enter Keyword Here" value= keyword required)

I checked my browser’s network tab after pressing enter on my index.pug and it seems that the GET request was successful and search.pug was received by the browser, but it’s just not rendered :/

Component causing elements with wire:transition in other component to disappear

In my application I added a second component to a view only to find an element within the first component would disappear whenever a property in the second component was changed.

I’ve stripped the problem back to its basics in a brand new Laravel app and the unexpected behaviour is still present. Here’s my code:

View:

<!DOCTYPE html>
<html>
    <head>
    @livewireStyles
    </head>
    <body>
    <livewire:test />
    <livewire:test2 />
    @livewireScripts
    </body>
</html>

Component 1:

<?php

namespace AppLivewire;

use LivewireComponent;

class Test extends Component
{
  public function render()
    {
      return view('livewire.test');
    }
}

Component 1 view:

<div>
    @if(true)
    <strong>First component</strong>
        <div wire:transition>
            Element <em>with</em> `wire:transition` attribute.
        </div>
        <div>
            Element <em>without</em> `wire:transition` attribute.
        </div>
    @endif
</div>

Component 2:

<?php

namespace AppLivewire;

use LivewireComponent;

class Test2 extends Component
{
    public $value = true;

    public function changeValue()
    {
        $this->value = !$this->value;
    }

    public function render()
    {
        return view('livewire.test2');
    }
}

Component 2 view:

<div wire:click="changeValue">
    @if($value == true)
        <div>
            <button>Second component.</button>
        </div>
    @endif
</div>

Whenever the ‘changeValue’ method is run the element in component 1 with the wire:transition attribute disappears.

I’ve created a quick repo with a vanilla Laravel install to show the problem here: https://github.com/jolora/livewire-bug

Creating PDF from HTML with Dynamic Header and Footer Using AJAX – PDF Generation Interrupted After File Upload

I have a problem creating pdf.
scenario: I create pdf from html. I need to dynamically create separate HTML for my footer and header areas.
Problem: After receiving my main HTML content according to my draft via ajax request, I download the file on the server for the footer. I open the file I downloaded and change the text in it with Replace. Then I upload it to the folder I specified with a new name. After the file is uploaded to the folder, it refreshes the page and my pdf creation process is interrupted.
I will be giving you my js codes and methods in the Controller below. What solution should I implement?
The line where the problem occurs: await System.IO.File.WriteAllTextAsync(footerFilePath, footerContent);
js codes:

function loadTemplateContent(pdfTemplateID) {

    var fDocumentGUID = $('#documentGUID').val();
    $.ajax({
        url: '/_Ajax/GetPDFTemplateContent',
        data: { pdfTemplateID: pdfTemplateID, fDocumentGUID: fDocumentGUID },
        success: function (data) {
            originalContent = data;
            CKEDITOR.instances['TemplateContent'].setData(data);
            //footerContent = data.footer;
        }

    });
}

method:

[HttpGet]
public async Task<IActionResult> GetPDFTemplateContent(int pdfTemplateID, Guid? fDocumentGUID)
{
    var template = await _serviceManager.PDFTemplates.GetByIdAsync(pdfTemplateID);
    if (template == null)
    {
        return Json(string.Empty);
        //return Json(new { header = string.Empty, content = string.Empty, footer = string.Empty });
    }
    string content = template.TemplateContent;
    string footerContent = string.Empty;

    if (fDocumentGUID.HasValue)
    {
        var fDocument = await _serviceManager.FDocuments.GetEntityAsync(a => a.GUID == fDocumentGUID.Value);
        if (fDocument != null)
        {
            var selectedDataVW = await _serviceManager.VW_FDocuments.GetEntityAsync(a => a.GUID == fDocumentGUID.Value);

            var customerAdress = _serviceManager.Customers.GetValue(a => a.GUID == selectedDataVW.CustomerGUID, "Adress");
            var responsibleMember = await _serviceManager.VW_Members.GetEntityAsync(a => a.MemberID == selectedDataVW.ResponsibleMemberID);
            var obligatoryMemberNames = await _MemberDataService.GetMemberIDsWithNamesAndTypes(fDocument.ObligatoryMemberIDs, false);
            var (infoMemberNames, infoMemberTypeNames) = await _MemberDataService.GetMemberIDsWithNamesAndTypes(fDocument.InfoMemberIDs, true);


            content = content.Replace("$$FDocNo$$", selectedDataVW.FDocNo);
            content = content.Replace("$$FDocDate$$", selectedDataVW.FDocDate.ToShortDateString());

            content = content.Replace("$$CustomerName$$", selectedDataVW.CustomerName);
            content = content.Replace("$$CustomerAdress$$", customerAdress);

            content = content.Replace("$$ResponsibleMember$$", responsibleMember.NameSurname);
            content = content.Replace("$$ResponsibleMemberTitle$$", responsibleMember.MemberTypeName);

            content = content.Replace("$$InfoMember$$", infoMemberNames);
            content = content.Replace("$$InfoMemberTitle$$", infoMemberTypeNames);

            content = content.Replace("$$ToplantiyaKatilanlar$$", obligatoryMemberNames.MemberNameSurname);
        }
    }

    //footer
    string footerUrl = $"https://tkba.tdub.org.tr/lib/Templates/{template.FooterText}";
    footerContent = await _PdfService.DownloadContent(footerUrl);
    string formattedDate = DateTime.Now.ToString("yyyyMMddHHmmssfff");
    var allowedFooters = new List<string> { "Footer_1.html", "Footer_3.html" };
    if (allowedFooters.Contains(template.FooterText))
    {
        var FooterFileName = $"{template.FooterText}-{formattedDate}.html";
        string footerFilePath = Path.Combine(_env.WebRootPath, "images/Uploads", FooterFileName);

        var fDocument = await _serviceManager.FDocuments.GetEntityAsync(a => a.GUID == fDocumentGUID.Value);
        var (infoMemberNames, infoMemberTypeNames) = await _MemberDataService.GetMemberIDsWithNamesAndTypes(fDocument.InfoMemberIDs, true);

        footerContent = footerContent.Replace("$$InfoMember$$", infoMemberNames);
        footerContent = footerContent.Replace("$$InfoMemberTitle$$", infoMemberTypeNames);

        await System.IO.File.WriteAllTextAsync(footerFilePath, footerContent);
        //footerContent = FooterFileName;
    }

    //footer


    //return Json(new { success = true, content = content, footer = footerContent });
    return Json(content);
}

When I select one of the drafts that come with the select list, the content of the relevant draft will be loaded, then I will download the footer field of the draft from the url on the server and replace the relevant fields. Afterwards, I want to upload the current footer to the folder. After uploading to the folder, I want to get the name of the current footer here and continue my pdf creation method.
my problem; After creating and uploading the file, it refreshes the page. In this way, I cannot create my html content as pdf.

NewRelic browser agent not logging anything in my Angular app

I placed the browser javascript snippet in the head tag right below the meta tag.

But it has not logged anything on the NewRelic UI for the last 1 hour.

We are getting the following error on the console: Uncaught SyntaxError: Invalid or unexpected token (Screenshot attached)

enter image description here

We copied and pasted the same code as given by the NewRelic UI at the time of setting up the app. I cleared the browser’s DNS cache as well, but it still has the same issue.

enter image description here

Cannot read properties of undefined function in React?

I am creating a weather app using ReactJS. Following is my code:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      temp: ""
    };
    this.getLocation = this.getLocation.bind(this);
    this.getWeather = this.getWeather.bind(this);
  }
  componentDidMount() {
    this.getLocation();
  }
  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success,error);
    }
    else {
      console.log("Not supported");
    }
    function success(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
      console.log(lat,lon);
      this.getWeather();
    }
    function error() {
      console.log("Unable to retrieve your location");
    }
  }
  getWeather() {
    fetch(`http://api.weatherapi.com/v1/current.json?key=${api}&q=${lat},${lon}&aqi=no`)
    .then((data) => data.json())
    .then((item) => {
      console.log(item);
    });
  }

api, lat and lon are constants I declared and initialized before this. This is giving the error:

Cannot read properties of undefined (reading 'getWeather')
    at success

How to create a clean function to render various images based on a prop with React and TypeScript

In my React and Typescript project I have to render some images (a small, medium or large) but based on e.g. a variant prop I have to render the relevant image.

I created a mapping for simplicity for the images data (or do I have to structure it differently?):

const ImageMapping = {
    exampleTypeOne: {
      ImageSmall: ImageSmallTypeOne,
      ImageMedium: ImageMediumTypeOne,
      ImageLarge: ImageLargeTypeOne,
    },
    exampleTypeTwo: {
      ImageSmall: ImageSmallTypeTwo,
      ImageMedium: ImageMediumTypeTwo,
      ImageLarge: ImageLargeTypeTwo,
    },
  };


return (

      <picture>
        <source media={`(max-width: ${breakPoints.xs}px)`} srcSet={ImageSmall} />
        <source media={`(max-width: ${breakPoints.md}px)`} srcSet={ImageMedium} />
        <img
          src={ImageLarge}
          alt="My alt"
          width="480"
          height="400"
        />
      </picture>
)

How do I create a clean and simple function to render the various images based on e.g. a variant prop like:

export type Props = {
  variant: 'typeOne' | 'typeTwo';
};

How can I center a component on the screen in React Native?

I’m having trouble centering a component on the screen using React Native. I’ve tried a few approaches, such as using justifyContent and alignItems, but haven’t been able to achieve the desired result.

My current code looks something like this:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

const App = () => {
  return (
    <View style={styles.container}>
      <Text>My Component</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    // Styles to center the component on the screen
    // I've tried justifyContent, alignItems, but without success
  },
});

export default App;

Could someone provide me with a simple solution to center this component on the screen? I appreciate it in advance!”

defaultValue option not selecting default value in Autocomplete Dropdown

stateNPAValue[formData.state.vale] = 0: "All",1: "959", 2: "203",3: "860", 4: "475" // API response for NPA data

const [selectedNamesState, setSelectedNamesState] = useState([]);

const transformedNpaData = stateNPAValue[formData.state.value].map((label, index) => ({
    label,
    value: index.toString()  // You can use the index as the value or any unique identifier
  }));

<Autocomplete
                multiple
                id="fixed-tags-demo"
                name="Npa"
                value={selectedNamesState}
                onChange={(event, newValue) => {
                  setSelectedNamesState(newValue)
                  NPAHandler(newValue);
                  changeHandleStateErrorRemove(event)
                }}                
                options={transformedNpaData}
                getOptionLabel={(option) => option.label.replace(/[[]']+/g, '')}
                defaultValue={[transformedNpaData[0].label]}
                renderTags={(tagValue, getTagProps) =>
                  tagValue.map((option, index) => (
                    <Chip
                      label={option.label.replace(/[[]']+/g, '')}
                      {...getTagProps({ index })}
                    />
                  ))
                }
                style={{ width: 500 }}
                renderInput={(params) => <TextField {...params} label={formData.state.value} />}
                isOptionEqualToValue={(option, value) => {
                  return option.value === value.value;
                }}
              />

I wanted to select “All” as a default value in multiselect dropdown but defaultValue option is not working. Please let me know what is wrong with this code.