Cannot swap values on next.js app even though swap function is getting called

I’ve created a currency converter app with next.js. It works fine. However I also try to insert a functionality that allows users to swap From and To currencies back and forth.

This is the function code:

 const swapCurrencies = () => {
   console.log("Before Swap:", convertFrom, convertTo);
   setConvertFrom(convertTo);
   setConvertTo(convertFrom);
   console.log("After Swap:", convertFrom, convertTo);
 };

This is the button:

  <button onClick={swapCurrencies}>
    Swap
  </button>

These are input fields for From and To currencies:

    <Input
      label="From:"
      dropdown={true}
      onChange={setConvertFrom}
      symbols={symbols}
    />
    <Input
      label="To:"
      dropdown={true}
      onChange={setConvertTo}
      symbols={symbols}
    />

Related snippet of input.js file:

    {(dropdown && (
      // Dropdown list for From & To currencies
      <select name="countries" onChange={(e) => onChange(e.target.value)} className="px-4 py-2 rounded-xl">
      {arrOfSymbols.map((symbol) => (
        <option value={symbol} key={arrOfSymbols.indexOf(symbol)}>
          {symbols[symbol]}
        </option>
      ))}

When I click on the Swap button, it doesn’t work. I’ve inspected on the console and found out that the function is getting called but the values are not getting swapped.

From the console:

Before Swap: USD EUR
After Swap: USD EUR

Can anyone advice me on what should I try to make this function work?

How to add role based auth to Nextjs with Next-auth & firebase

I’m currently working on implementing role-based authentication using NextAuth.js in my Next.js application. I’ve followed the documentation provided by NextAuth.js, but I encountered an error when trying to add role-based authentication to my API routes.

I’m using TypeScript and my API route file is located at pages/api/auth/[..nextauth]/route.ts.

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import {signInWithEmailAndPassword} from 'firebase/auth';
import auth from '@/app/lib/auth';


export const authOptions = {
 
  secret: process.env.AUTH_SECRET,
  pages: {
    signIn: '/signin'
  },
  session: {
    strategy: "jwt" as const,
    maxAge: 3600,
  },

  providers: [
    CredentialsProvider({
      profile(profile) {
        return {
          role: profile.role ?? "user",
        }
      },
      name: 'Credentials',
      credentials: {},
      async authorize(credentials): Promise<any> {
        return await signInWithEmailAndPassword(auth, (credentials as any).email || '', (credentials as any).password || '')
          .then(userCredential => {
            if (userCredential.user) {
              return userCredential.user;
            }
            return null;
          })
          .catch(error => (console.log(error)))
  .catch((error) => {
    console.log(error);
  });
      }
    })
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) token.role = user.role;
      return token;
    },
    async session({ session, token }) {
      if (session?.user) session.user.role = token.role;
      return session;
    },
  },
}
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST}

Could someone please help me understand why this error is happening and how I can properly implement role-based authentication with NextAuth.js in my API routes?

What I Tried:

  • Using NextAuth.js Documentation: I’m setting up role-based authentication in my Next.js app by following the NextAuth.js documentation.

  • Copying Code: I copied code snippets from the documentation to implement role-based authentication.

  • Encountering Error: After implementing the code, I encountered an error.

Remove data from localStorage

I need to remove the PTO from both localStorage and the screen. Are there duplicate parts of the code, i.e. is it well written? If not, can you write the correct code?

const removePtoInfo = async (event) => {
    const clickedIcon = event.currentTarget;
    const parentForm = clickedIcon.closest('.pto-info');
    const isConfirmed = confirm(`Do you want to delete this PTO?`);

    if (isConfirmed) {
        try {
            const ptoId = parentForm.dataset.id;

            const res = await fetch(`https://jsonplaceholder.typicode.com/users/${ptoId}`, {
                method: "DELETE"
            });

            if (!res.ok) {
                throw new Error('Failed to delete PTO');
            }

            let ptoList = JSON.parse(localStorage.getItem('ptoList'));

            const indexToRemove = ptoList.findIndex(pto => pto.id === ptoId);

            if (indexToRemove !== -1) {
                ptoList.splice(indexToRemove, 1);

                localStorage.setItem('ptoList', JSON.stringify(ptoList));
                
                parentForm.remove();
                
                displayPTOList(ptoList);
            } 
            else {
                console.error('PTO not found in the list.');
            }
        } catch (error) {
            console.error(error);
        }
    }
}

How to snap touch slider to scroll position using JavaScript?

I am creating a store and on my landing page I want to create a touch-enabled slider/carousel with products (like the one on mobile https://www.nike.com/es).

I have created an overflowing container (.slider-container) with 6 “product-slots” (.slide) and I have set overflow to scroll in css. Now I want that whenever someone slides (touchmove) a bit, it snaps to the next product once released (touchend)

I have tried something in JS but I am an total amateur… (I don’t want to use SliderJs, etc. – trying to do it myself and learn a bit)

Here is HTML and CSS:

        <div class="slider-container">

            <div class="slide">

                <img src="HOODIE_GRIS_FRONT_720x (1).png" style="width: 275px;">

                <p class="preview-product-title">Cool Shorts</p>
                <p class="preview-color">Blue Navy</p>
                <p class="preview-price">€29</p>
            </div>
            <div class="slide">

                <img src="HOODIE_GRIS_FRONT_720x (1).png" style="width: 275px;">

                <p class="preview-product-title">Cool Shorts</p>
                <p class="preview-color">Blue Navy</p>
                <p class="preview-price">€29</p>
            </div>
            <div class="slide">

                <img src="HOODIE_GRIS_FRONT_720x (1).png" style="width: 275px;">

                <p class="preview-product-title">Cool Shorts</p>
                <p class="preview-color">Blue Navy</p>
                <p class="preview-price">€29</p>
            </div>
            <div class="slide">

                <img src="HOODIE_GRIS_FRONT_720x (1).png" style="width: 275px;">

                <p class="preview-product-title">Cool Shorts</p>
                <p class="preview-color">Blue Navy</p>
                <p class="preview-price">€29</p>
            </div>
            <div class="slide">

                <img src="HOODIE_GRIS_FRONT_720x (1).png" style="width: 275px;">

                <p class="preview-product-title">Cool Shorts</p>
                <p class="preview-color">Blue Navy</p>
                <p class="preview-price">€29</p>
            </div>
            <div class="slide">

                <img src="HOODIE_GRIS_FRONT_720x (1).png" style="width: 275px;">

                <p class="preview-product-title">Cool Shorts</p>
                <p class="preview-color">Blue Navy</p>
                <p class="preview-price">€29</p>
            </div>

        </div>
*{
    margin: 0;
    padding: 0;
    font-family: "Roboto Condensed", sans-serif;
 }
 
 
 html{
     scroll-behavior:smooth;
     overflow-x: hidden;
 }
 
 body {
     overflow-x: hidden;
 }

.slider-container{
    display: flex;
    overflow: scroll;
}

.slide{
    min-width: 275px;
    margin: 20px 0 40px 0;
    padding-left: 10px;

}

.preview-product-title{
font-size: 17px;
 padding: 2px 0 2px 0;
}

.preview-color{
    font-size: 17px;
    color: gray;
    padding-bottom: 2px;


}


.preview-price{
    font-size: 17px;
    font-weight: bold;


}



.slide:first-child{
    margin: 20px 0 40px 15px;
}

.slide:last-child{
    margin: 20px 20px 40px 0;
}

This is what I have tried on JS and basically, whenever you try to scroll, you get sent back to the beginning (slider.scrollLeft = 0)

let startPos = 0
let sliderScroll = 0
let prevPos = 0
let currentPos = 0

const slider = document.querySelector('.slider-container')
const slideWidth = document.querySelector('.slide').getBoundingClientRect().width

function getPositionX(event) {
    return
    event.touches[0].clientX
}

function touchStart(event) {
    startPos = getPositionX(event)
    sliderScroll = slider.scrollLeft
}

function touchMove(event) {
    currentPos = getPositionX(event)
}

function touchEnd() {
    let calcNumber = Math.round((sliderScroll + Math.abs(startPos - currentPos)) / slideWidth)
    let setScrollPos = calcNumber * slideWidth
    
    
    slider.scrollTo({
        left: setScrollPos,
        behaviour: 'smooth'
    })

}

slider.addEventListener('touchstart', touchStart)
slider.addEventListener('touchmove', touchMove)
slider.addEventListener('touchend', touchEnd)

How to Correctly Wrap and Display Text with displayChar Aligned with Transparent Textarea Overlay

The default textarea behavior wraps with omitted spaces at the end and beginning of rows. Note: lines in this are for multi-lined code block format with line break characters. This should also display that correctly; as well as long “single-line” wrapping phrases

<div class="layout-container" >
  <div  phx-update="ignore" id="timer-box">
  <div id="js-timer">READY</div>
  </div>
    <div class="js-content" style="position: relative;">
    <!-- JavaScript Managed Area  -->
      <div id="phrase-data" data-phrase-text={@phrase.text}></div>
      <div  phx-update="ignore" id="js-text-area" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
      <div class="js-typing-area" style="position: relative;">
      <pre style="position: absolute; top 0; left: 0; width: 100%; height: 100%; margin: 0; padding: 0; box-sizing: border-box; font-family: monospace; font-size: 10px; line-height: 120%; width: 100%; height: 100%;">
      <code style="position: absolute; top 0; left: 0; width: 100%; height: 100% white-space: pre-wrap;" id="js-typing-area"></code></pre>
      </div>
      </div>
    <form class="typing-area" phx-change="input" phx-submit="submit" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2;">
    <textarea class="user-input" id="code-editor" name="user_input" phx-hook = "AutoFocus" phx-debounce="1000"
    style="background-color: transparent; color: transparent; border: none; width: 100%; height: 100%; font-family: monospace; font-size: 10px; line-height: 120%; box-sizing: border-box;"></textarea>
      </form>


    </div>
    <div class="elixir-content">
      <div id="elixir-content">
        <pre ><code class="elixir-content" ><%= render_typing_area(@phrase, @user_input) %></code></pre>
      </div>
    </div>
  </div>

and my current JS rendering function goes line by line, and char by char within, and creates for non-breaking overflow word wrap. But each space is now a separate “word”, but this keeps spaces after wrap, breaking the overlay.

Also, now this isn’t doing newlines on multi-line code blocks anymore q.q

function updateJSTypingArea(phrase, userInput) {
    const codeElement = document.querySelector('#js-typing-area');
    if (!codeElement) return;
  
    const phraseLines = phrase.split('n');
    const userInputLines = userInput.split('n');
    let htmlContent = '';
  
    phraseLines.forEach((phraseLine, lineIndex) => {
      const userInputLine = userInputLines[lineIndex] || '';
      let lineHtmlContent = '';
      let wordHtmlContent = '';
      let extraSpacesHandled = false;
      let isLineBlank = true; // Assume the line is blank until proven otherwise
      let isLineStart = true; // Flag to track the start of a linea
      for (let i = 0; i < phraseLine.length; i++) {
        const phraseChar = phraseLine[i];
        const userInputChar = userInputLine[i] || ' ';
        let classList = ['ghost-text'];
        let displayChar = phraseChar === ' ' ? '&nbsp;' : phraseChar;
  
        if (userInputChar !== undefined) {
          
          if (phraseChar === userInputChar || (phraseChar === ' ' && userInputChar === ' ')) {
            classList = ['correct-input'];
            isLineBlank = false; // There's content in this line
          } else if (userInputChar !== ' ') {
            classList = ['error'];
            isLineBlank = false; // There's content in this line
            displayChar = userInputChar === ' ' ? '▄' : userInputChar; // Use ▄ for error spaces
          }
        }
         // Handle the zero-width space for the first character in a line or after a newline
      
  // Append the character to the word HTML, handling spaces as their own "word"
        if (phraseChar === ' ') {
          if (isLineStart) {
            displayChar = '&#8203;'; // Use zero-width space if the actual space is the first character
            isLineStart = false; // Reset flag after handling the first character'
          } else{
            isLineStart = false; // Any non-space character means we're no longer at the start
          }
          // Close the previous word and start a new span for the space
          lineHtmlContent += `<span class="word">${wordHtmlContent}</span>`;
          wordHtmlContent = ''; // Reset word HTML content
          // Add the space as its own word span
          lineHtmlContent += `<span class="word"><span class="${classList.join(' ')}">${displayChar}</span></span>`;
      } else {
          wordHtmlContent += `<span class="${classList.join(' ')}">${displayChar}</span>`;
      }

      // Ensure the last word is added if it's not followed by a space
      if (i === phraseLine.length - 1 && wordHtmlContent !== ' ') {
          lineHtmlContent += `<span class="word">${wordHtmlContent}</span>`;
      }
    }
      //   wordHtmlContent += `<span class="${classList.join(' ')}">${displayChar}</span>`;//changed from space to blank
  
      //   if (phraseChar === ' ' || i === phraseLine.length - 1) {
      //     lineHtmlContent += `<span class="word">${wordHtmlContent}</span>`;
      //     wordHtmlContent = '';
      //   }
      // }
  
      // Handle trailing spaces in user input as correct, if they exist beyond the phrase length
      if (userInputLine.length > phraseLine.length) {
        const extraChars = userInputLine.slice(phraseLine.length);
        if (/^s*$/.test(extraChars)) { // Check if all extra characters are spaces
          extraChars.split('').forEach(() => {
            lineHtmlContent += `<span class="correct">&nbsp;</span>`;
          });
          extraSpacesHandled = true;
        }
      }
  
      // If there were no extra spaces or other characters that were handled as correct,
      // handle any remaining extra characters as errors.
      if (!extraSpacesHandled && userInputLine.length > phraseLine.length) {
        const extraChars = userInputLine.slice(phraseLine.length);
        extraChars.split('').forEach(char => {
          const displayChar = char === ' ' ? '&nbsp;' : char;
          lineHtmlContent += `<span class="error">${displayChar}</span>`;
        });
      }
      if (isLineBlank) {
        // If the line is still considered blank, insert a zero-width space
        lineHtmlContent += `<div class="line">&#8203;</div>`;
      }
      htmlContent += `<div class="line">${lineHtmlContent}</div>`;
    });
  
    codeElement.innerHTML = htmlContent;
  }
.typing-overlay-container {
  /* Adjust dimensions as needed */
  width: 100%;
  height: auto;
  min-height: 100px; /* Ensure it's tall enough for your content */
}
/* Ensure the textarea is transparent and overlays the feedback area */


pre code {
  white-space: pre-wrap; /* Allow long lines to wrap */
  word-wrap: break-word; /* Ensure words can break and wrap to the next line */
  overflow-wrap: break-word; /* Similar to word-wrap, for better compatibility */
}


.layout-container {
  position: relative;
  width: 100%; /* or specific width as needed */
}

.js-content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%; /* or specific width as needed */
  height: 400px; /* Adjust based on content */
  z-index: 1;
}
.js-typing-area, .user-input {
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
}
.user-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%; /* Ensure it covers the container width */
  min-height: 100%;
  z-index: 0;
  color: transparent;
  border: none;
  outline: none;
  font-family: monospace;
  font-size: 10px;
  line-height: 120%;
  box-sizing: border-box; /* Ensure padding and border are included in width/height */
  padding: 0; /* Remove padding */
  margin: 0; /* Remove margin */
  caret-color: rgb(1, 68, 12);
  letter-spacing: normal; /* Ensure letter spacing is consistent */
  word-spacing: normal; /* Ensure word spacing is consistent */
}
.typing-area{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%; /* Ensure it covers the container width */
  min-height: 100%; /* Adjust if you have a specific height in mind or use 100% for full container height */
  z-index: 2; /* Ensure the textarea is above the content it overlays */
  background-color: transparent;
   /* To keep the caret visible */
  border: none;
  outline: none;
  font-family: monospace;
  font-size: 10px;
  line-height: 120%;
  letter-spacing: normal; /* Ensure letter spacing is consistent */
  word-spacing: normal; /* Ensure word spacing is consistent */
  margin: 0;
  padding: 0; /* Adjust as necessary, but keep them the same */
  box-sizing: border-box;
}
.typing-area2{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%; /* Ensure it covers the container width */
  min-height: 100%; /* Adjust if you have a specific height in mind or use 100% for full container height */
  z-index: 2; /* Ensure the textarea is above the content it overlays */
 
  border: none;
  outline: none;
  font-family: monospace;
  font-size: 10px;
  line-height: 120%;
  letter-spacing: normal; /* Ensure letter spacing is consistent */
  word-spacing: normal; /* Ensure word spacing is consistent */
  margin: 0;
  padding: 0; /* Adjust as necessary, but keep them the same */
  box-sizing: border-box;
}
.elixir-content {
  position: relative;
  
  width: 100%;
}
.line {
   /* display: block;Ensures each .line starts on a new line */
  white-space: pre-wrap; /* Maintains whitespace but allows normal wrapping within the .line */
   /* margin-bottom: 1em;Adds space between lines, adjust as needed */
}
.line, .word, span {
  display: inline; /* .word {display: inline-block;} Treat words as inline blocks to manage spacing and wrapping */

  margin: 0;
  padding: 0;
  font-family: monospace;
  font-size: 10px; /* Adjust based on your setup */
  line-height: normal; /* Adjust based on your setup */
}

.word {
  white-space: nowrap; /* Prevent words from wrapping */
display: inline-block;
}

span.ghost-text, span.error {
  display: inline-block; /* Treat characters individually but maintain flow */
  width: 1ch; /* Use the 'ch' unit for width based on character size */
}
.js-typing-area, .user-input, pre, code {
  position: absolute;
  top: 0;
  left: 0;
  font-family: monospace;
  font-size: 10px;
  line-height: 120%;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

Automatic load section, but close if another html css

I want that my section is automatically shown when the website is loading, but hided when one of the other sections are loaded. How can I do that?

<section id="overview" style="display: none;">
    Test
    <p>Example</p>
</section>

I already tried to work with JavaScript, but my code there was garbage and helped nothing lol

Thanks for every help, greets!

Client missing intents discord.js

So im trying to code a discord bot and im just doing simple coding and nothing to advanced yet and i run into this problem

C:UsersantiaDesktopfafnode_modulesdiscord.jssrcclientClient.js:512
      throw new DiscordjsTypeError(ErrorCodes.ClientMissingIntents);
      ^

TypeError [ClientMissingIntents]: Valid intents must be provided for the Client.
    at Client._validateOptions (C:UsersantiaDesktopfafnode_modulesdiscord.jssrcclientClient.js:512:13)
    at new Client (C:UsersantiaDesktopfafnode_modulesdiscord.jssrcclientClient.js:80:10)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:49 {
  code: 'ClientMissingIntents'
}

Node.js v20.11.1

So i looked it up and somebody said to add this to my code

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

but now it says TypeError: Cannot read properties of undefined (reading ‘FLAGS’)

const Discord = require("discord.js");
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const ms = require('ms')

const prefix = "y!"

client.on('ready', () => {
    client.user.setActivity(` y!help | Currently in ${client.guilds.cache.size} Servers | I also have ${client.users.cache.size} users`);
    console.log('I am online')
});

client.on('message', message => {
    if(message.content === "y!ping") {
        message.channel.send(`Pong! Latency is ${Date.now() - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`)
    }
});

client.on('message', message => {
    if(message.content === "y!embedtest" || message.content === "y!et") {
        const embed = new Discord.MessageEmbed()
        .setTitle('Embed')
        .setDescription('Embeds are working fine')
        .setTimestamp()
        .setImage('https://i.imgur.com/xL5FJ7b.jpg')
        message.channel.send(embed);
    }
});

client.login(token);

^^^ My code

Call API with Javascript that includes Header and includes Token Space API Key

I have a challenge where I am building a webpage with html and javascript to have the user input the workpaper ID and then an output populates for the user. Bonus points if the data retrieved from the json output can be used in calculations.

Below is what I have so far:

enter image description here

Ideally the user would input their workpaper (ie:SWHC052); there would be another input for the version (ie: 02)

The submit button would populate the data retrieved from the filters the user enters. Some information:

enter image description here

example would be “Token 12345b73a0b6378bcfbb4ddb1f9e86f5b4762676” (FAKE)

There has to be a space between the word “Token” and the API Key

Below is the API URL:

Example:
https://www.caetrm.com/api/v1/measures/SWHC020/01/permutations?limit=10&offset=10

Ideally if the user inputted the workpaper as SWHC052
And if the user inputted the version as 02

https://www.caetrm.com/api/v1/measures/{workpaper from user input}/{version from user input}/permutations?limit=10&offset=10

Then I should receive the data from that call

As a bonus only, it would be great once the data is retrieved to format as a table for the user as well as parse and calculate depending on values retrieved.

Thank you so much for any assistance!

Element-specific CSS gets applied to all elements of that type

I’ve created a website, https://www.example.com. Now, I also created a mobile subdomain, where the four pages I originally created are combined into one long-scroll. When I manually go to m.example.com, this works just fine, but I’ve also printed some cards with QR code referencing the main domain previously. Since a QR code is more likely to be scanned from a mobile device, I want to add some code to the homepage that redirects any “mobile devices” to m.example.com automatically, but when I try implementing this in JS, my redirect ends up sending me to example.com/m.example.com instead. How can I redirect to the actual subdomain?

My code so far is pretty simple:

//Redirect to mobile subdomain if on mobile device
if (screen.width <= 699) {
    window.location = "m.example.com";
}

I’ve also tried document.location and I’ve tried referencing based on the document tree – tried pointing to ./mobile/index.php, where the root folder is where the main homepage’s index.php resides, and so where I figured I’d be redirecting from. Note that my JS is in the ./inc directory, but whether I include ./ or not (or even ././), computer says no 🙁
I’ve also tried looking at .htaccess, which seems fine for referrals, but I didn’t see anything about how to do a conditional referral there either. I’m using PHP and JS, and of course HTML and CSS, so any solution using those languages is preferred, but I’ll take whatever works.

Empty body in fetch request

frontend:

 fetch(location.href, {
  method: "POST",
  headers: {
    "Content-type": "application/json"
  },
  body: JSON.stringify({
    user: document.getElementById("user").innerText,
    call: "Upvote",
    cname: "comp_name"
  })
},(data) => {
  console.log(data)
})

backend:

router.post("/",(req,res) =>{
    console.log(req.body)
}

the response of console.log is just {} instead of the json data

I also tried to log the whole response but the body was still empty and i also tried to check for any bug that might be caused in JSON.stringify by putting it in a variable and then doing the fetch but it didn’t help

In todo , When a task is edited, the changes are visible on the console and after refreshing the page, but they are not visible in tasks list

const TodoCard = ({ title, id, delid }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [Inputs, setInputs] = useState({
    title: "",
  });

  useEffect(() => {
    setInputs({ title });
  }, [title]);

  const change = (e) => {
    const { name, value } = e.target;
    setInputs({ ...Inputs, [name]: value });
  };

  const handleEdit = () => {
    setIsEditing(true);
    console.log(title);
  };

  const handleUpdate = async () => {
    setIsEditing(false);
    await axios
      .put(`http://localhost:1000/api/v2/updateTask/${id}`, Inputs)
      .then((response) => {
        console.log(response);
        toast.success("Task Added");
      });
    console.log(Inputs);
    console.log("title is  : ", title);
  };

  return (
    <div>
      <div className="task-cont">
        {isEditing ? (
          <input
            name="title"
            type="text"
            value={Inputs.title}
            onChange={change}
          />
        ) : (
          <div className="tasks">{title}</div>
        )}
        <div className="task-icons">
          {isEditing ? (
            <ImCheckmark className="icons" onClick={handleUpdate} />
          ) : (
            <>
              <MdDelete className="icons" onClick={() => delid(id)} />
              <MdModeEditOutline
                className="icons"
                onClick={handleEdit}
                name="title"
              />
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default TodoCard;

I would like to view the edited tasks in the input field. Currently, they only appear after a page refresh, but I want them to update immediately. There seems to be an issue with state management in React. The inputs are updated, but the title is not updating without a refresh.

In the TodoCard component, the useState hook is used to manage the state of whether the task is being edited (isEditing) and the input value (Inputs). The useEffect hook is used to update the input value when the title prop changes.

The handleEdit function sets the isEditing state to true, which switches the component to edit mode. The handleUpdate function sends a PUT request to update the task on the server and sets the isEditing state to false, which switches the component back to view mode.

Using UIKit methods in Angular App fails my Jest Test Suite with error ReferenceError: CSS is not defined

Versions

  • Angular ~16.2.0
  • Jest ^29.4.1
  • UIKit ^3.17.8
  • Node 20.10.0
  • NPM 10.2.5

I understand that Node doesn’t have access to the CSS API because Client/Server differences, however I don’t know how to rectify this issue correctly. I’ve made a few attempts following similar issues I’ve found, but they haven’t lined up with my scenario.

// app.component.ts
import * as UIKit from 'uikit'

...

ngOnInit(): void {
  ...
  UIkit.default.modal('#welcome-modal').show();
}

On trying to run my test suit I get the following error:
enter image description here

Does anyone have any info on rectifying this issue? It would be greatly appreciated as this is getting in the way of the setting up of my pipeline. I can provide more information if needed.

how to check letter by letter in a word and make change accordignly?? html js… typing game

typing game…. im working on this menu for my game.. and i have this problem:

i have 2 words on the screen and a typing zone where it checks for keys and display it on screen…

i want for every correct letter in the typing zone if it matches the letters of one of the words … the letter would turn “green” else “red”…. sorry for my bad english

<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Madimi+One&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Typo game</title>
</head>
<body>
    <label id="playerInput">start</label>
    <label id="options">options</label>
    <label id="TypeZone">sssssss</label>
  <script src="script.js"></script>
</body>
</html>
*{
  font-family: "Madimi One", sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body{
  height: 100vh;
  background-color: black;
}
#playerInput{
  position: absolute;
  top: 40%;
  left: 45%;
  transform: translate(-50% -50%);
  font-size: 3em;
  color: aliceblue;
}
#options{
  position: absolute;
  top: 55%;
  left: 43%;
  transform: translate(-50% -50%);
  font-size: 3em;
  color: aliceblue;
}
#TypeZone{
  position: absolute;
  top: 70%;
  left: 67%;
  transform: translate(-50% -50%);
  font-size: 3em;
  color: aliceblue;
}
const start= document.querySelector("#playerInput");
const get_start = [...start.textContent]

const options = document.querySelector("#options");
const get_options = [...options.textContent]

let inputX = "";
let getInputX = true;



const type = document.querySelector("#TypeZone")



// get input from keyboard and display on screen
document.addEventListener("keydown", function(event) {
  
    if (getInputX) {
      inputX += event.key;
      type.textContent = inputX;

      
      if (inputX.length >= get_options.length) {
          getInputX = false;
      }
    }
    if (get_start.includes(event.key)){
      start.style.color ="green"; /// what i want to do is to turn letter green for each correct letter and so on
    }
    else{
      start.style.color = "red";
    }
    if (get_options.includes(event.key)){
      options.style.color ="green"; /// 
    }
    else{
      options.style.color = "red";
    }

  // if typed start or options >> start the game
  if (inputX === "start" || inputX === "options"){
    window.location.href = "game.html";
  }
  
});

here s what i tried so far