Email password reset link does not work with deployed React application

I recently finished a project in React, only the client side was developed, I used a ready-made API. One of the features is password reset, which in the development environment was working perfectly, but after deploying to the platform (I think the platform is irrelevant as the same problem occurred on both Vercel and Netlify).

The problem is that the link to reset the password is sent to the user’s email, but when clicked, the reset page is not found, I need help, both to fix the bug and to find out the cause in future projects.

Here is the repository, feel free to suggest changes and ask for more details, thanks: (https://github.com/hermesonbastos/Dogs-React)

enter image description here

enter image description here

api.jsx

export function PASSWORD_LOST(body) {
  return {
    url: API_URL + "/api/password/lost",
    options: {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    },
  };
}

export function PASSWORD_RESET(body) {
  return {
    url: API_URL + "/api/password/reset",
    options: {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    },
  };
}

Login.jsx

import React from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import LoginForm from "./LoginForm";
import LoginCreate from "./LoginCreate";
import LoginPasswordLost from "./LoginPasswordLost";
import LoginPasswordReset from "./LoginPasswordReset";
import { UserContext } from "../../UserContext";
import styles from "./Login.module.css";
import NotFound from "../NotFound";

const Login = () => {
  const { login } = React.useContext(UserContext);

  if (login === true) return <Navigate to="/conta" />;
  return (
    <section className={styles.login}>
      <div className={styles.forms}>
        <Routes>
          <Route path="/" element={<LoginForm />} />
          <Route path="criar" element={<LoginCreate />} />
          <Route path="perdeu" element={<LoginPasswordLost />} />
          <Route path="resetar" element={<LoginPasswordReset />} />
          <Route path="*" element={<NotFound />} />
        </Routes>
      </div>
    </section>
  );
};

export default Login;

LoginPasswordReset.jsx

import React from "react";
import Input from "../Forms/Input";
import Button from "../Forms/Button";
import useForm from "../../Hooks/useForm";
import { PASSWORD_RESET } from "../../api";
import useFetch from "../../Hooks/useFetch";
import Error from "../Helper/Error";
import { useNavigate } from "react-router-dom";
import Head from "../Helper/Head";

const LoginPasswordReset = () => {
  const [key, setKey] = React.useState("");
  const [login, setLogin] = React.useState("");
  const password = useForm();
  const { error, loading, request } = useFetch();
  const navigate = useNavigate();

  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const key = params.get("key");
    const login = params.get("login");
    if (key) setKey(key);
    if (login) setLogin(login);
  }, []);

  async function handleSubmit(event) {
    event.preventDefault();
    if (password.validate()) {
      const { url, options } = PASSWORD_RESET({
        login,
        key,
        password: password.value,
      });
      const { response } = await request(url, options);
      if (response.ok) navigate("/login");
    }
  }

  return (
    <section className="animeLeft">
      <Head title="Resete a senha" />
      <h1 className="title">Resete a Senha</h1>
      <form onSubmit={handleSubmit}>
        <Input
          label="Nova Senha"
          type="password"
          name="password"
          {...password}
        />
        {loading ? (
          <Button disabled>Resetando...</Button>
        ) : (
          <Button>Resetar</Button>
        )}
      </form>
      <Error error={error} />
    </section>
  );
};

export default LoginPasswordReset;

Ui-based-integration-testing can not get expected value from ElementID

First and foremost. I am a total beginner. I have no prior knowledge or consensus so I have no I what I am doing, but I know that this is for an assignment. I have been stuck on this one part for hours at this point. For a little context. I am using JSDOM UI integrated testing for my assignment. For this example, we are using a roman numeral converter. More specifically an old roman numeral to modern roman numeral.

This is my romanNumerals.html file

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="romanNumerals.css">
        <script src="romanNumerals.js" defer></script>
    </head>
    <body>
        <div class="results">
            <div class="result">
                <div id="old-roman-result"></div>
                "Old" Roman Numeral
            </div>
            <div class="result">
                <div id="modern-roman-result"></div>
                "Modern" Roman Numeral
            </div>
        </div>
        <form id="arabic-number-form">
            <label>
                Arabic number (1-3999)
                <input type="number" min="1" max="3999" id="arabic-number" name="arabic-number" />
            </label>
            <button>Convert to "modern" Roman</button>
        </form>
    </body>
</html>

This is my romanNumerals.js file

/**
 * This function initializes the JavaScript functionality after the HTML content is loaded.
 */
window.addEventListener('DOMContentLoaded', () => {
    const arabicNumberInput = document.getElementById("arabic-number");
    const form = document.getElementById("arabic-number-form");
    const oldRomanResult = document.getElementById("old-roman-result");
    const modernRomanResult = document.getElementById("modern-roman-result");

    /*
     * Clear Arabic number input field when the page first loads.
     */
    arabicNumberInput.value = "";

    /*
     * Add a listener to the Arabic number input field to listen for typing and
     * update the "old" Roman numeral result "live" as the user types.  If the
     * value input by the user can't be converted to an "old" Roman numeral,
     * don't display any value.
     */
    arabicNumberInput.addEventListener("input", function () {
        modernRomanResult.textContent = "";
        const arabicNumber = parseInt(arabicNumberInput.value);
        try {
            oldRomanResult.textContent = convertToOldRoman(arabicNumber);
        } catch (err) {
            oldRomanResult.textContent = "";
        }
    });

    /*
     * When the user actually submits the form, send a request to the API described
     * here to convert the number to a "modern" Roman numeral:
     *
     * https://helloacm.com/tools/romans/
     *
     * If an error occurs in the translation, an error message is displayed.
     */
    form.addEventListener("submit", async function (event) {
        event.preventDefault();
        clearErrorMessages();
        const arabicNumber = arabicNumberInput.value;
        try {
            const response = await fetch(
                `https://romans.justyy.workers.dev/api/romans/?n=${arabicNumber}`
            );
            const data = await response.json();
            if (data.error) {
                displayError(data.error);
            } else {
                modernRomanResult.textContent = data.result;
            }
        } catch (err) {
            displayError(err.message);
        }
    });

    /*
     * This function displays an error message to the user if the translation
     * request failed for any reason.
     */
    function displayError(errorMsg) {
        const errorDiv = document.createElement("div");
        errorDiv.classList.add("error");
        errorDiv.setAttribute("role", "alert");
        errorDiv.innerHTML = "<h3>❌ Error</h3>";

        /*
         * The error message may have come from the outside world, so we have to
         * treat it cautiously, making sure it's not executed as HTML code.
         */
        const errorMsgP = document.createElement("p");
        errorMsgP.textContent = errorMsg;
        errorDiv.appendChild(errorMsgP);

        form.appendChild(errorDiv);
    }

    /*
     * This function removes any error message currently being displayed to the
     * user.
     */
    function clearErrorMessages() {
        const errors = form.querySelectorAll(".error");
        errors.forEach(function (error) {
            error.remove();
        });
    }

    /*
     * This table represents the conversions between Roman digits and Arabic values.
     */
    const conversionTable = {
        "M": 1000,
        "C": 100,
        "L": 50,
        "X": 10,
        "V": 5,
        "I": 1
    };

    /**
     * This function converts an Arabic number into the corresponding "old" Roman
     * numeral.  Old Roman numerals are based only on addition.  For example, the
     * Arabic number 9 is "VIIII" in old Roman numerals (it's "IX" in modern Roman
     * numerals).
     *
     * @param {number} input A numeric value representing the Arabic number to
     *   convert to old Roman numerals.  Must be in the range 1-3999.  Any decimal
     *   part of the number is ignored.
     *
     * @throws {RangeError} Throws a RangeError if the input value is a number
     *   outside the range 1-3999.
     * @throws {Error} Throws an Error if the input is not a number.
     *
     * @returns {string} Returns a string containing the old Roman numeral
     *   conversion for the specified input value.
     */
    function convertToOldRoman(input) {
        if (input === undefined || typeof input !== "number") {
            throw Error("Expected a number parameter");
        }
        if (input < 1 || input > 3999) {
            throw RangeError("Input must be in range 1-3999");
        }

        /*
         * Cycle through Roman digits from greatest (M) to least (I).  For each
         * digit, subtract the corresponding Arabic value from the input number
         * as many times as possible, adding an instance of the current Roman
         * to the resultint translation for each subtraction.
         */
        const romanDigits = Object.keys(conversionTable);
        let currRomanIdx = 0;
        let result = "";
        while (input > 0 && currRomanIdx < romanDigits.length) {
            const currRomanDigit = romanDigits[currRomanIdx];
            const currArabicValue = conversionTable[currRomanDigit];
            while (input >= currArabicValue) {
                result += currRomanDigit;
                input -= currArabicValue;
            }
            currRomanIdx++;
        }
        return result;
    }

});

And this is my romanNumerals.test.js file

/**
 * @jest-environment jsdom
 */

// Polyfill TextEncoder
global.TextEncoder = require('util').TextEncoder;
global.TextDecoder = require('util').TextDecoder;

const fs = require("fs");
const { JSDOM } = require("jsdom");
const { fireEvent, waitFor } = require("@testing-library/dom");
const userEvent = require("@testing-library/user-event").default;
const axios = require("axios");
const MockAdapter = require("axios-mock-adapter");

// Load HTML content
const htmlContent = fs.readFileSync("./romanNumerals/romanNumerals.html", "utf8");
const { document } = new JSDOM(htmlContent).window;

// Mock the API response for conversion to "modern" Roman numerals
const mock = new MockAdapter(axios);
mock.onGet("https://romans.justyy.workers.dev/api/romans/?n=123").reply(200, { result: "CXXIII" });

function initDomFromFiles() {
    document.body.innerHTML = htmlContent;
    require("./romanNumerals.js");
}

test("should update 'modern' Roman numeral result on form submission", async () => {
    // Arrange
    initDomFromFiles();
    const arabicNumberInput = document.getElementById("arabic-number");
    const convertButton = document.querySelector("button");
    const modernRomanResult = document.getElementById("modern-roman-result");

    // Act:
    const user = userEvent.setup();
    await user.type(arabicNumberInput, "123");
    await user.click(convertButton);
    // Assert
    await waitFor(() => {
        expect(document.getElementById("modern-roman-result").textContent).toBe("CXXIII");
    });
});

I am at a complete and utter loss. I run npx jest. The test fails. because the actual value is nothing, but it should be CXXIII I tried using the API, I tried using an imported function from the js file. Nothing is working for me. I’d appreciate any help I can get.

Uncaught ReferenceError: route is not defined at HTMLAnchorElement.onclick

Having a huge push back here in a small weekend project.

I am building a simple SPA application using JS, HTML, and TailwindCSS, and currently having a problem, apparently, with routing when running the application.

This is the form under “pages/home.html”

<form id="journalForm" action="/" method="post" class="bg-white rounded-lg shadow p-6">
    <ul>
        <input id="locationName" type="text" placeholder="Location name" class="rounded-md bg-gray-100 p-2" />
    </ul>
    <ul>
        <input id="journalNotes" type="text" placeholder="Add your notes here!" class="rounded-md bg-gray-100 p-2" />
    </ul>
    <div class="button-container">
        <button id="addPhoto" class="rounded-md p-2 bg-gray-100 text-black">Add images &#128248;</button>
        <button type="button" id="addEntry" class="rounded-full bg-gray-100 text-black text-sm">+</button>
    </div>
</form>

This is my “js/main.js” file:

export class JournalEntries {
    constructor() {
        this.entries = JSON.parse(localStorage.getItem('journalEntries')) || [];
        this.bindForm();
        this.renderEntries();
    }

    bindForm() {
        document.getElementById('addEntry').addEventListener('click', () => {
            const locationName = document.getElementById('locationName').value;
            const journalNotes = document.getElementById('journalNotes').value;
            if (!locationName || !journalNotes) {
                alert('Please fill in all fields.');
                return;
            }
            this.add({ locationName, journalNotes });
            document.getElementById('journalForm').reset(); 
        });
    }

    add(entry) {
        this.entries = [entry, ...this.entries];
        this.update();
        this.save();
    }

    save() {
        localStorage.setItem('journalEntries', JSON.stringify(this.entries));
    }

    update() {
        this.renderEntries();
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new JournalEntries();
});

And, finally, this is my router, inside “js/router.js”:

export class Router {
    routes = {};

    add(routeName, page) {
        this.routes[routeName] = page
    }

    route(event) {
        console.log("Route event activated")
        event = event || window.event
        event.preventDefault()

        window.history.pushState({}, "", event.target.href);

        this.handle()
    }

    handle() {
        const { pathname } = window.location
        const route = this.routes[pathname]

        fetch(route)
            .then(data => data.text())
            .then(html => {
                document.querySelector("#app").innerHTML = html;
            });

        console.log(route);
    }
}

I keep getting the following errors:

1

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at JournalEntries.bindForm (main.js:9:44)
    at new JournalEntries (main.js:4:14)
    at HTMLDocument.<anonymous> (main.js:37:5)

2

Uncaught ReferenceError: route is not defined
    at HTMLAnchorElement.onclick

3

GET http://127.0.0.1:8080/home 404 (Not Found)

And being very confused. Can someone provide a little guidance?

Thank you!

Tried fixing classes, inserting console.log alerts, and all that.

Nest framework error Delete `␍` eslint(prettier)

I just decided to try the nest framework, and here’s an error like this, I don’t know how to fix it. I didn’t touch anything at all, I just started it

Code prettier:

{
  "singleQuote": true,
  "trailingComma": "all"
}

Code eslint:

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    tsconfigRootDir: __dirname,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
  },
};

Here is a photo of the error

I tried deleting something prettier but nothing changed.

Function call inside template with variable interpolation

I am learning JS templates and found the following example:

function hash(a, b) {
    return a + "##" + b;
}
let count = 3;
let a = `foo ${hash ` bar ${count} baz`}`;
console.log(a);

result is : foo bar , baz##3

Could anyone explain:

  1. Why hash function is called without using parentheses –()?
  2. This result – foo bar , baz##3?

Flask javascript chatbot responds in terminal but not in frontend

the problem is that the chatbot input text works ok, responds correctly when tested in Terminal but displays no response in Frontend .

18/Feb/2024 18:03:30] “POST /predict HTTP/1.1” 200
I am testing it with print(response) in Terminal and it works as planned.

So far the issue that I see is marked by VSCode in the html file (the brackets for {{request.script_root|tojson}}):

Property assigment expected: javascript

<script>
    $SCRIPT_ROOT =  {{request.script_root|tojson}};
</script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>

I have been spending hours reviewing the code but cannot find a solution.

Appreciate the orientation.

Why is my Node.js function not changing the admin field to true?

I am making a simple message board app and some logic that changes certain users admin field to true based on their email address. Everything else is working as expected except this functionality.

My approach to this problem was adding an optional admin field to my User model that has a default boolean value of false. On registration my app will look for a predetermined email and if it finds a match, it will then update the admin value to true. It seems pretty simple but it is not working. Here is a sample of the code so you can see my thought process (I took out the stuff that is relevant to this question):

//This is my user registration logic
exports.register_post = asyncHandler(async (req, res, next) => {
    try {
        const admin = await User.findOne({email: process.env.ADMIN_EMAIL}).exec(); //find user based on the email they register will


        if (admin) {
            try {
                const result = await admin.updateOne({ email: process.env.ADMIN_EMAIL }, { admin: true }).exec(); //update the 
            } catch (err) {
                console.error('Error updating admin status:', err);
                return res.status(500).send('Error updating admin status');
            }
        }
        // Create new user
        const user = new User({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email,
            password: hashedPassword, // Use the hashed password
        });

        await user.save();

        // Redirect after successful registration
        res.redirect("/");
    } catch (err) {
        next(err);
    }
});
const UserSchema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    email: {type: String, required: true},
    password: {type: String, required: true},
    posts: {type: Schema.Types.ObjectId, ref: "Post"},
    admin: {type: Boolean, default: false},
})

The thing that is confusing me the most is that my error handling code is not being triggered either. It just creates the user like it would before I added this function. The only thing that I can think of as a solution would to be to move the logic to change the admin field AFTER the new user is created. However, that did not work for me either.

Redirect not working in ReactJS using Navigate inside Delete request

This is the function where I am calling delete, here navigate to ‘/’ is not working, please help me

const deleteClick = async (_id) => {
  try {
    const url = API_URL;
    // Make the delete request using axios
    const response = await axios.delete(url);
    console.log(`Deleted post with ID ${_id}`);
    // Navigate only after a successful deletion
    navigate('/');
  } catch (error) {
    console.error('Error deleting blog:', error);
    // You might want to handle errors or show a message to the user here
  }
};

Polyfill for ReadableStream.from in browser?

ReadableStream.from for browsers is currently only supported in Firefox. I found the Node implementation in JavaScript, but it uses a lot of internal native node functions. Likewise, ReadableStream.from.toString() in Firefox’s console reveals that its implementation is also a native function.

Is there a pure JavaScript implementation I can polyfill in temporarily? Perhaps using ReadableStreams constructor? I imagine the appropriate pull and cancel callbacks can be written based on the underlying iterator.

Summing up value of multiple objects in list

In MeubelComponent, I manipulate a list (selectedMeubels) dynamically. It’s passed to Page.js, where I encounter issues calculating the total size due to MeubelComponent rendering multiple times. This occurs because each instance maintains its own state, leading to discrepancies. What is the best way to solve this issue?


{/* ... imports */}

const MeubelPage = ({ selectedRoom }) => {
    {/* ... (existing code) */}

    const [selectedMeubels, setSelectedMeubels] = useState([]);
    

    useEffect(() => {
        // Fetch meubels data based on selectedRoom using API[selectedRoom]
        if (selectedRoom && API[selectedRoom]) {
            setMeubels(API[selectedRoom]);
        }
    }, [selectedRoom]);

    const addToSelectedMeubels = (id) => {
        setSelectedMeubels((prevSelected) => [...prevSelected, meubels.find(item => item.id === id)]);
    };

    const removeFromSelectedMeubels = (id) => {
        setSelectedMeubels((prevSelected) => prevSelected.filter(item => item.id !== id));
    };
    return (
  
{/* ... (existing code) */}

                {meubels.map((item) => (
                    <div 
                        key={item.id} 
                        onClick={() => {
                            if (selectedMeubels.some(selected => selected.id === item.id)) 
                           {
                                removeFromSelectedMeubels(item.id);
                            } else {
                                addToSelectedMeubels(item.id);
                            }
                        }}
                    >
                        <Meubel 
                            meubel={item} 
                            selectedClassName={
                                selectedMeubels.some(selected => selected.id === item.id) 
                                    ? "absolute inset-x-0 bottom-0 h-2 bg-gradient-to-r from-green-300 via-green-500 to-green-600"
                                    : "absolute inset-x-0 bottom-0 h-2 bg-gradient-to-r from-orange-300 via-orange-500 to-orange-600"
                            }
                        />
                    </div>
                ))}
            </div>

            {/* ... (existing code) */}
        </div>
    );
};

export default MeubelPage;

{/* ... imports */}

const Page = () => {
    const [open, setOpen] = React.useState(1);
    const handleOpen = (value) => setOpen(open === value ? 0 : value);
    // State to store klantgegevens and ruimtes
    const [klantgegevens, setKlantgegevens] = useState({});
    const [ruimtes, setRuimtes] = useState([]);
    // State to store selected meubels
    const [selectedMeubels, setSelectedMeubels] = useState([]);
    // State to store the total size of selected items
    const [totalSize, setTotalSize] = useState(0);

    useEffect(() => {
        // Retrieve the data from local storage when on the client side
        if (typeof window !== 'undefined') {
            const storedKlantgegevens = JSON.parse(localStorage.getItem("klantgegevens")) || {};
            setKlantgegevens(storedKlantgegevens);

            const storedRuimtes = JSON.parse(localStorage.getItem("geselecteerderuimtes")) || [];
            setRuimtes(storedRuimtes);
        }
    }, []);

    useEffect(() => {
        // Calculate the sum total of sizes when selectedMeubels changes
        const sumSizes = selectedMeubels.reduce((total, selectedItem) => total + selectedItem.size, 0);
        setTotalSize(sumSizes);
    }, [selectedMeubels]);

    const salutation = klantgegevens.aanhef
        ? `${klantgegevens.aanhef}. ${klantgegevens.voornaam && klantgegevens.voornaam[0]} ${klantgegevens.tussenvoegsel || ''} ${klantgegevens.achternaam}`
        : "Gegevens ophalen...";

    return (
        <main>
            <NavBar />
            <div className="m-6 px-4 mb-4">
                <Steps />
                <div className="h-10 rounded-lg px-8 py-3 mb-4 rounded-lg bg-white-200 shadow-md lg:col-span-3 lg:p-12">
                    <p className="text-xl font-medium text-gray-600">{salutation}</p>
                </div>

                <div className="h-25 rounded-lg px-8 py-3 mb-4 rounded-lg bg-white-200 shadow-md lg:col-span-3 lg:p-12">
                    <p className="text-xl font-medium text-gray-600"> Gekozen ruimtes</p>
                </div>
                <div className="rounded-lg px-8 py-3 mb-4 rounded-lg bg-white-200 shadow-xl lg:col-span-3 lg:p-12">
                    <div className="grid grid-cols-1 gap-4 lg:grid-cols-1 lg:gap-8">
                        {ruimtes && ruimtes.length > 0 && (
                            <>
                                {ruimtes.map((ruimte, index) => (
                                    <Accordion key={index} open={open === index + 1}>
                                        <AccordionHeader className="text-xl font-medium text-gray-600" onClick={() => handleOpen(index + 1)}>
                                            {`${ruimte} ${open === index + 1 ? '▼' : '▲'}`}
                                        </AccordionHeader>
                                        <AccordionBody>
                                            <MeubelPage selectedRoom={ruimte} setSelectedMeubels={setSelectedMeubels} />
                                        </AccordionBody>
                                    </Accordion>
                                ))}
                            </>
                        )}
                    </div>
                    <div className="mt-4">
                        <p className="text-xl font-medium text-gray-600">Total Size of Selected Items: {totalSize}</p>
                    </div>
                </div>
            </div>
        </main>
    );
};

export default Page;

updating modelValue from the child component inside the v-for loop vue3

When I’m changing (updating) the modelValue from the child component into the parent component it changes values back in all of the looped (with v-for) child components values. So when I change from 15 to 25 – the value 25 is changed in all of the child components but not in the single one I intended to.

//Parent component
 <script setup>
   const options = ref(['15', '25', '30'])
  let selectedOption = ref('15')
<script>
<template>
  <div class="product" 
    v-for="product in productsStore.cart" 
    :key="product.id">
    <SelectComponent 
      :options="options"
      v-model="selectedOption"/>
   </div>
</template>

//Child component
<script setup>
const props= defineProps({
    options: {
      type: Array
    },
    modelValue: {
      type: String,
      required: true,
      default: '15' 
    }
  })
  const emits = defineEmits(['update:modelValue'])
  
  const selectOption = (option) => {
    emits('update:modelValue', option)
  }
</script>
<template>
  <h4 class="list--title">{{ props.modelValue }}</h4>
  <p class="list__options-item list--sorting-options-item" 
     v-for="option in props.options" 
     :key="option"
     @click="() => selectOption(option)"
     >{{option}}
   </p>
</template>

Removing image in javascript [closed]

I am trying to remove an image:

if (playerChoice === scenario.correctOption) {
   // Handle correct choices for the original scenario
   if (scenario.options[playerChoice] === "Administer epinephrine") {
     increaseVitalSigns(); // Call increaseVitalSigns without any parameter
   } else if (scenario.options[playerChoice] === "Start CPR") {
     startCPR();
     **document.getElementById('img').remove();**
   }
   
 } else {
   // Handle incorrect choice for the original scenario
   const messageElement = document.getElementById('message');
   messageElement.textContent = 'Patient has no pulse!';
 }

However the document.getElementById('img').remove(); line does not remove the image.

The element is called upon later in the code:

function startCPR() {
 isCPRStarted = true;
 cprInterval = setInterval(updateVitalSigns, 1000); // Call updateVitalSigns every second for CPR simulation
 oxygenInterval = setInterval(updateOxygenSaturation, 2000); // Update oxygen saturation every 2 seconds

 // Show EKG image
 showEKGImage();
}

function showEKGImage() {
 // Create an image element
 const ekgImage = document.createElement("img");
 ekgImage.src = "ekg_image.png"; // Replace "ekg_image.png" with the path to your EKG image
 ekgImage.alt = "EKG Image";
 ekgImage.style.width = "auto"; // Set width to auto to maintain original size
 ekgImage.style.height = "auto"; // Set height to auto to maintain original size

 // Append the image to the game container
 const gameContainer = document.querySelector(".game-container");
 gameContainer.appendChild(ekgImage);

}

However startCPR function allows it to appear, and I want to be disappear after. Can someone please offer insight and help for me.

Thank you!

I have tried adjustments in syntax.

Javascript – functional programming concept whith api requests and mutation of input: can it ever be pure?

  1. making api requests is considered not pure. in functional programming that should create pure functions, it is impossible to make api requests within a function AND be pure, right?

  2. the function below uses recursion and also changes the input itself. Changing input is considered a side effect, so s I understand its not pure? I wonder, for cases like the below on, the most common way is usually using recursion like below. Does it also mean that sometimes functions just cant be pure and cannot be made pure so 100% functional programming cannot be really achieved?

const flatten = (arr,result=[]) => {
     for(let i=0;i<arr.length;i++) {
       if(Array.isArray(arr[i])) {
          flatten(arr[i],result)
       }
       else  {
         result.push(arr[i]);
       }
     }
     return result;
 }

 const arr=[1,2,[5,3,4,[7,8,9,[10,11]]]];

Importing the header file in the App.jsx file

I have the problem in importing the header file in the React app file, once I try to import it gives me this message “‘Header’ is defined but never used.” please help me, for the one who is familiar with react.js . Also how can I solve this problem easily once I come across this problem or another problem similar to this?