Saving the original state of a class in javascript [duplicate]

Let’s say I have a class

class Apple {
    constructor(color){
        this.state = {
            color: color
        }
    }

    getState(){
        return this.state;
    }

    setState(state){
        this.state = state;
    }

    turnGreen(){
        this.state.color = "Green";
    }
}

and if i do

let apple = new Apple("Red");

const originalState = apple.getState();

apple.turnGreen();             
console.log(apple.getState());   //{color: 'Green'}

apple.setState(originalState);
console.log(apple.getState());   //{color: 'Green'}

How come const originalState gets changed to ‘Green’ as well?
And is there any way to save the original state of the apple?
Thanks in advance

Web code is just not working – text keeps popping up after animation

So I’m trying to animate three phrases to zoom and fade in, then fade out consecutively, with an infinite loop. But after the first loop iteration the text pops up with 100% opacity for a few seconds then suddenly disappears after animation is complete.

It does not do this if I play the animations only once.

See GIF: https://i.gyazo.com/24574a5112f8920ce1a37a2fa65f4a40.gif

Here’s the source code:

<div class="anim-box">
  <h4 class="loop-phrase" id="move">Move Better</h4>
  <h4 class="loop-phrase" id="heal">Heal Faster</h4>
  <h4 class="loop-phrase" id="live">Live Longer</h4>
</div>
.anim-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.loop-phrase {
  font-size: 24px;
  opacity: 0;
  position: absolute;
    color: #fff;
}

#move {
  animation: move 2s linear;
}

#heal {
  animation: heal 2s linear;
  animation-delay: 2s;
}

#live {
  animation: live 2s linear;
  animation-delay: 4s;
}

@keyframes move {
  0% {
    transform: scale(1);
    opacity: 0;
  }
  50% {
    transform: scale(2);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

@keyframes heal {
  0% {
    transform: scale(1);
    opacity: 0;
  }
  50% {
    transform: scale(2);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

@keyframes live {
  0% {
    transform: scale(1);
    opacity: 0;
  }
  50% {
    transform: scale(2);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}
function animateText() {
  const moveText = document.getElementById('move');
  const healText = document.getElementById('heal');
  const liveText = document.getElementById('live');

  let counter = 0;

  setInterval(() => {
    if (counter === 0) {
      moveText.style.opacity = 0;
      setTimeout(() => {
        moveText.style.opacity = 1;
        moveText.style.animation = 'none';
        void moveText.offsetWidth;
        moveText.style.animation = 'move 2s linear';
        counter++;
      }, 1000);
    } else if (counter === 1) {
      healText.style.opacity = 0;
      setTimeout(() => {
        healText.style.opacity = 1;
        healText.style.animation = 'none';
        void healText.offsetWidth;
        healText.style.animation = 'heal 2s linear';
        counter++;
      }, 1000);
    } else if (counter === 2) {
      liveText.style.opacity = 0;
      setTimeout(() => {
        liveText.style.opacity = 1;
        liveText.style.animation = 'none';
        void liveText.offsetWidth;
        liveText.style.animation = 'live 2s linear';
        counter = 0;
      }, 1000);
    }
  }, 3000);
}

window.onload = function() {
  animateText();
};

Tried to adjust the opacity to be 0% during the 1 second delay in between text animations to no avail. I am really stuck.

How to not have the screen scroll down to show the first item in a flatlist with an inverted flatlist React Native?

I have an inverted flatlist to show a news feed, but the most recent news item is the last item in the data object to the flatlist, hence why I am using an inverted flatlist. But an inverted flatlist pushes the screen down when it is first rendered to be able to see the first item (last on the page) at the bottom. I want to have the last item in the data (the most recent piece of news) at the top of the page when it is initially rendered. How can I resolve this?

<FlatList
                data={Object.values(dataObject)}
                renderItem={({ item }) => <NewsWidget article={item} />}
                contentContainerStyle={styles.body}
                ListFooterComponent={<View style={{ height: 5 }} />}
                inverted
            />

This attachment is what is initially rendered. As you can see, there is more news (the most recent) if you were to scroll up. That is what I want to see first at the top.

I tried setting the initialScrollIndex={0}, but this did not seem to do anything. I want to see the most recent news at the top, and not have the page scrolled down to see the last piece of news at the bottom.

Why in next.js ” use client ” in top of component give me this error?

when i use “use client” in the top of my component i get this error

`      "dependencies": {
        "eslint": "8.38.0",
        "eslint-config-next": "13.3.0",
        "next": "13.3.0",
        "react": "18.2.0",
        "react-dom": "18.2.0"
      }`
`'use client'
export default function Home() {
  console.log("====================================");
  console.log("Test");
  console.log("====================================");
  return (
    <>
      <h1>Next.js</h1>
    </>
  );
}
`

enter image description here

i try use client-side-render and i had error

getElementsByTagName recursively on a page with iFrames

Trying to use helpful code provided at using document.getElementsByTagName on a page with iFrames – elements inside the iframe are not being picked up but both samples seem to look into first “level” of iframes and not inside of iframes inside other iframes.

Tried:

const subtreeSet = (root, theset) => {
    if (!theset) theset=new Set();
    if (!root || theset.has(root)) return theset;
    theset.add(root);
    if (root.shadowRoot) {
        Array.from(root.shadowRoot.children).forEach(child => subtreeSet(child, theset));
    } else {
        if (root.tagName === 'IFRAME') { try { root=root.contentDocument.body; theset.add(root); } catch (err) { root=null; /* CORS */ } }
        if (root && root.getElementsByTagName) for (const child of root.getElementsByTagName('a')) subtreeSet(child, theset);
    }
    return theset;
}

console.log(subtreeSet(document));

expected to see all links, but saw only ones not inside nested iframes.

Testing async functions that fetch data using jquery with Jest

I am trying to test an async function that fetches data from a json file and stores it in a variable

The function I am trying to test (present in registration.js):

async function readJSONFile(url) {
    const data = await $.getJSON(url);
    return data;
}

let returnedData = await readJSONFile(testURL);

module.exports = readJSONFile;

How can I create a test file using jest in order to test this function?

I tried this code for testing but for some reason, it is not reading the main javascript file

const readJSONFile = require("./registration.js/readJSONFile");


test("check if the data is retrieved", async () => {
    const testData = {
        "courseName" : {
            "instrName" : "profName",
            "location" : "classLocation",
            "timings" : "classTimings"
        }
    }

    const data = await  $.getJSON(testURL);
    expect(data).toBe(testData)
});

The error:

Cannot find module './JS/registration.js/readJSONFile' from 'Jest Testing/registration.test.js'

Project Structure:

| Jest Testing
    | registration.test.js

| JS
    | registration.js

rn does not get converted into carriage return and new line

If I do:

let str1 = 'Line1rnLine2rnLine3rn'

console.log(str1) gives output:

Line 1
Line 2
Line 3

But I have a js function which I pass a string into (lets call it str2) with the same content, and when I console.log it I see:

'Line1rnLine2rnLine3rn'

Instead of:

Line 1
Line 2
Line 3

What do I need to do with str2 to give it same behaviour as str1?

Best practices for optimizing JavaScript performance in low-power devices?

Description: I am developing a web application that will be used on low-power devices, such as IoT devices or older mobile phones. I want to ensure that the JavaScript code is as efficient and optimized as possible to ensure a smooth user experience. What are some best practices for optimizing JavaScript performance in these types of devices? How can I reduce the size of JavaScript files and minimize CPU and memory usage? Are there any specific frameworks or libraries that are particularly well-suited for low-power devices? I would appreciate any advice or tips on how to make my JavaScript code as performant as possible on these types of devices.

I have not tried anything yet

Keep arguments accessible in callback c#

If some variable of my code is not ready I would keep an Action and its arguments to be called later on. So I keep the action and arguments in Tuple, like so:

    private (Action<string, string>, string[]) delayedTask;

    private void OnAuthNotAvailable(string email, string password) {
        delayedTask = ((string email, string password) => {
            Task.Run(() => {
                SignInWithEmailAndPasswordAsync(email, password);
            });
        }, new string[2] { email, password });
    }

So then I can call the delayedTask:

delayedTask.Item1?.Invoke(delayedTask.Item2[0], delayedTask.Item2[1]);

Is there a preferrable way to delay code execution than keeping the logic and the arguments in a tuple or a class? I would like to call my action where it has access to its arguments so that I don’t need to keep them for the deferred call.

Thinking about Javascript, where you would have a nested function and the inner has access to the scope of the outer, so you can create the logic by calling the outer and in later call to the inner function there is access to the outer’s function scope, so to the arguments of interest.

Autocomplete disabled when using typescript union type checking

I’m trying to get the typescript autocomplete to work with a function like this :

interface WeatherData {
  coord: { lon: number; lat: number };
}

const fetchWeatherData = async (
  location: string
): Promise<WeatherData | Error> => {
  try {
    const res = await axios.get(
      `/weathr?q=${location}&APPID=${process.env.API_KEY}`
    );
    return res.data;
  } catch (e) {
    return new Error("Couldn't fetch weather data");
  }
};

It will return the data If network request is successful otherwise an error with a custom message.

But autocomplete is completely disabled this way and I can’t access any fields I defined in WeatherData interface :

autocomplete

How can I use the autocomplete feature with typescript union type checking ?

How can I optimize publishing react component as a node module?

I have developed and published a node module which is a React component.

Here are its links.
https://www.npmjs.com/package/mui-datagrid-full-edit
https://github.com/prettyblueberry/mui-datagrid-full-edit

Of course, the module works well, but it has some unnecessary files and dependencies. The files and dependencies are for its development, so I cannot remove them in dev project.

Here is its package.json

{
  "name": "mui-datagrid-full-edit",
  "version": "1.1.0",
  "description": "A full functioned react MUI grid component with CRUD and an easy way of @mui/x-data-grid",
  
  ...
  
  "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "@emotion/react": "^11.7.1",
    "@emotion/styled": "^11.6.0",
    "@mui/icons-material": "^5.4.1",
    "@mui/material": "^5.4.1",
    "@mui/x-data-grid": "^5.17.25",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "core-js": "^3.29.1",
    "xlsx": "^0.18.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  
  ...

  "devDependencies": {
    "@babel/cli": "^7.21.0",
    "@babel/core": "^7.21.0",
    "@babel/preset-env": "^7.20.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1"
  },
  "main": "dist/index.js",
  "module": "dist/index.js",
  
   ...
}

Here is its file structure.
Screenshot of Structure

To solve it, I updated dependencies and devDependencies in package.json several times, but it seems it didn’t help me.
I also want to publish only files and folders like dist folder and packages.json for usage, except files like index.js and App.js for its development and testing.

To do it, I think package.json should works like two versions – a version for dev and a version for publishing, but not sure.

How can I do?

How to pass in parameters from client side to server side code in Sveltekit?

I’ve been trying to run a query to a Supabase database that needs a dog breed passed through and will return metrics about it, the breed is defined on the client side. I was able to get the server side query to run but the value is not going through.

+page.svelte

export let metrics;
  export let data;

  const getAllDogs = async () => {
    const { metrics: data } = load({ dog: dog_val });
    metrics = data;
  };
  
  onMount(async () => {
    getAllDogs();
  })


+page.server.js

import supabase from "../../lib/db";

//Method to get all dog breeds
export const load = async ({dog}) => {
  const getAllMetrics = async () => {
    try {
      let { data, error } = await supabase
        .from("dogs")
        .select(
          "avg_size, avg_obedience, avg_compassion, avg_health, avg_cleanliness, avg_energy"
        )
        .eq("Breed", dog);
      console.log(data)
      console.log(dog)
      return data;
    } catch (e) {
      console.error(e);
    }
  };
  return {
    metrics: getAllMetrics(dog)
  }
};

React router dom wont work when I deploy with gh-pages

in App.js:

return (
    <BrowserRouter basename="/">
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route exact path="/home" element={<Home />} />
        <Route exact path="/header" element={<div><Header links={"/"}/><Me /><Footer /></div>} />
        <Route exact path="/me" element={<div><Header links={"/"}/><Me /><Footer /></div>} />
        <Route exact path="/About" element={<div><Header  links={"/"}/> <About /> <Footer /></div>} />
        <Route exact path="/projects" element={<div><Header  links={"/"}/> <Projects /> <Footer /></div>} />
        <Route exact path="/skills" element={<div><Header  links={"/"}/> <Skills /> <Footer /></div>} />
        <Route exact path="/contact" element={<div><Header  links={"/"}/> <Contact /> <Footer /></div>} />
        <Route path="*" element={<ErrorPage />} />
      </Routes>
    </BrowserRouter>
  );
}

This is working correctly at localhost, and first deploy was working.
I haven’t change app.js and I fix some bugs When I deployed, then it haven’t work again.
Now I am deploying to github with npm run deploy, only home page is working.

in package.json:

{
  "homepage": "http://ayazvefa.dev/",
  "name": "vefa-ayaz",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "aos": "^3.0.0-beta.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.9.0",
    "react-script-tag": "^1.1.2",
    "react-scripts": "5.0.1",
    "typed.js": "^2.0.132",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },

github pages screenshoot

and here to source code
and here to website link

I don’t know where is the problem, I use hashrouter(it was working(/#/)), I added basename(website link, “/”) and it wasn’t working again Where is the problem? why browserrouter wont work?

How to modify any text with code in WordPress?

On the products page, I have a text shown in the image around it with a red circle. I want to change it with the code. I mean modify it using PHP or JS. I don’t know how in WordPress

Can you help me knowing that the ID for this Text is ID:(sumosubs_plan_message)

enter image description here

SvelteKit with FastAPI in DockerCompose

I have an issue understanding how to make an API call to my FastAPI Docker container from SvelteKit Docker container running in Docker-compose and preserve Cookies set by FastAPI.

I need to post a formData with EMAIL and PASSWORD fields from SvelteKit to FastAPI. I’m trying to use Actions in SvelteKit to make the call from the page.server.js

export const actions = {
  login: async (event) => {
    const formValues = await event.request.formData();
    const email = formValues.get("email");
    const password = formValues.get("password");

    const formData = new FormData();
    formData.append("email", email);
    formData.append("password", "1");

    const res = await event.fetch(
      "http://fastapi_backend:8000/web_api/users/sessions",
      {
        method: "POST",
        body: formData,
        credentials: "include", // include cookies in the request
      }
    );

I can extract the cookie from the response and set it to the browser no problem:

const jwt = res.headers.get("set-cookie").split('"')[1];
event.cookies.set("jwt", jwt);

However, when I make another request again I expect the Cookies to be sent with the event.fetch but my FastAPI container does not see any. This is expected as it’s stated in SvelteKit Docs:

Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.
SvelteKit Docs

I can not imagine how to do this now. I’m testing this workflow outside of Docker-compose now.

All I know is that if I make this API call from the page.svelte in browser I wouldn’t have access to http://fastapi_backend:8000 which is the Docker-compose name of the FastAPI container.

How should I do this? Is the only real way to do this is to expose the FastAPI container to the outside and make the call from the browser from page.svelte?

Please help!

I’ve tested FastAPI with Postman and it successfully sends and receives cookies.
I’ve also tried making the call from the browser from page.svelte and it works.