How to load a .css file after each path/page/url?

I’m working on project React.js based.

I’m not a expert on Rect.js. They gave me a job to modify a open-source project made of React.js

So, I see the way of writting css is by javascript api instead raw .css. At least on this project all is written by Javascript “useStyles” module.

All I want is to run a .css file inside assets dir, so that It will run after the rendering of every page change.

I tried simply importing it on root file “App.js”; it works somwhow, but got bugs when changing page thoughtout React.js router functions or Link tag. In other hand, they work after reloading page.

Where and how to call my file.css?

I tried simply importing it on root file “App.js”; it works somwhow, but got bugs when changing page thoughtout React.js router functions or tag. In other hand, they work after reloading page.

FormData is Empty Objectin NextJS 14 when try to console [duplicate]

I am new to NextJs Trying to update user record with image but when before loop all form data values show but after loop when try to console the fromData{} blank object. below is the code
I try to send data through the FormData(), but the data is not saved in it even values are correctly populated and image data is also showing before loop, running the console.log(formDataToSend) leaves the FormData empty. I thought it would be because of the React states but it still doesn’t work


const EditUser = ({ params }) => {
    let userId = params.edituser;
    const [form, setForm] = useState({
        name: '',
        image: null, // Initialize image as null
    });
    const handleNameChange = (event) => {
        setForm(prevForm => ({
            ...prevForm,
            name: event.target.value,
        }));
    };
    const handleFileChange = (event) => {
        setForm(prevForm => ({
            ...prevForm,
            image: event.target.files[0], // Update image with the selected file
        }));
    };
    useEffect(() => {
        const fetchUserData = async () => {
            try {
                const response = await fetch(`/api/users/${userId}`);
                if (response.ok) {
                    const userData = await response.json();
                    setForm(userData.result);
                } else {
                    console.error('Failed to fetch user data');
                }
            } catch (error) {
                console.error('Error fetching user data:', error);
            }
        };
        fetchUserData();
    }, [userId]);
    const handleSubmit = async (event) => {
        event.preventDefault();
        try {
            const formDataToSend = new FormData(form);
            formDataToSend.append('name', form.name);
            formDataToSend.append('image', form.image); // Append the image file to formDataToSend
            const response = await fetch(`/api/users/${userId}`, {
                method: 'PUT',
                body: formDataToSend,
            });
            console.log(formDataToSend);
            if (response.ok) {
                console.log('User updated successfully');
            } else {
                console.error('Failed to update user');
            }
        } catch (error) {
            console.error('Error updating user:', error);
        }
    };
    return (        
            <form onSubmit={handleSubmit}>
                <input type="text" name="name" className="bg-blue-200 p-2 m-2" value={form.name} onChange={handleNameChange} placeholder="Name" />
                <input type="file" name="image" className="bg-blue-200 p-2 m-2" onChange={handleFileChange} />
                <button type="submit" className="bg-green-500 p-2 m-2">Update</button>
            </form>        
    );
};
export default EditUser;

Can anyone help what i did wrong where exatly the issue comes?

Implementation on HTTP Only/Secure cookie in Angular

Im trying to set http only cookie in Angular17:

import { CookieService } from 'ngx-cookie-service';
async login(formObject: any) {
    try {
      const res = await axios.post(`${this.url}`, formObject);
      if (res.status !== 200) return;
      this.token = res.data.token;
      this.cookieService.set(
        'authToken', // Customize cookie name
        this.token,
        {
          expires: new Date(Date.now() + 3600 * 1000),
          path: '/',
          domain: window.location.hostname,
          secure: true,
        },
      );
      console.log('http cookie set!');
    } catch (error) {
      console.error(error);
    }
  }

but i am still able to see the cookie in dev tools.
This library has only a secure flag, but it doesnt work as well as http only cookie.
How to set Http Only Cookie in Angular?

JsonPath, how to get the records’ ids with the minimal value of an attribute?

I have the following json data:

{"data": [{"ticket": "249 [DH-249]", "id": 249, "priority": 3, "title": "kUYWr7gWGH", "queue": {"title": "Django Helpdesk", "id": 1}, "status": "Open", "created": "4u00a0hours ago", "due_date": "13u00a0hours ago", "assigned_to": "uUAKA3ZA 2rg8oS9X", "submitter": "[email protected]", "row_class": "", "time_spent": "", "kbitem": ""}, {"ticket": "250 [DH-250]", "id": 250, "priority": 3, "title": "3kEpyPXp4", "queue": {"title": "Django Helpdesk", "id": 1}, "status": "Open", "created": "4u00a0hours ago", "due_date": "13u00a0hours ago", "assigned_to": "None", "submitter": "[email protected]", "row_class": "", "time_spent": "", "kbitem": ""}], "recordsFiltered": 195, "recordsTotal": 195, "draw": 1} 

How can i get an array of IDs where the priority is equal to minimal? For example, if the minimal priority is 3 in the data, I need to get id=249, id=250 (there’s more data usually)

I have tried using the JsonPath expression gpt gave me: $.data[?(@.priority == $.data[*].priority.min())].id but it does not work

Why Math.max with an Array Returns NaN in JavaScript? [duplicate]

I’m still new to Javascript. I have already tried to find information on the Internet and on publics, but have not yet come to an answer.

Guys, who knows why the program outputs NaN?

Javascript code:

let arr = [9, 23, 0, -24.5, 34, 11, 41, 3, -3.2, 3];
let arrmax = Math.max(arr);
console.log(arrmax);

ChatGPT writes that there are no errors and that the answer should be 41.

But when I write the code in one line like this, it works:

console.log("Largest number:", Math.max(9, 23, 0, -24.5, 34, 11, 41, 3, -3.2, 3));

Difference between go and js on float64

I know javascript has problems when number goes big, usual thing is that trailing digits will be truncated to zero. And I wonder what that looks like in golang, so I write a program:

see https://go.dev/play/p/2rbKFNiupQ_6

package main

import "fmt"

func main() {
    var v1 float64 = 1876219900889841660
    var v2 float64 = 1876219900889841661
    var v3 float64 = 1876219900889841662
    var v4 float64 = 1876219900889841663
    var v5 float64 = 1876219900889841664
    var v6 float64 = 1876219900889841665
    var v7 float64 = 1876219900889841666
    var v8 float64 = 1876219900889841667
    var v9 float64 = 1876219900889841668
    fmt.Printf("v1==v2: %vn", v1 == v2)      // true
    fmt.Printf("v2==v3: %vn", v2 == v3)      // true
    fmt.Printf("v3==v4: %vn", v3 == v4)      // true
    fmt.Printf("v4==v5: %vn", v4 == v5)      // true
    fmt.Printf("v5==v6: %vn", v5 == v6)      // true
    fmt.Printf("v6==v7: %vn", v6 == v7)      // true
    fmt.Printf("v7==v8: %vn", v7 == v8)      // true
    fmt.Printf("v8==v9: %vn", v8 == v9)      // true
    fmt.Printf("int64(v4): %dn", int64(v4))  // 1876219900889841664
    fmt.Printf("int64(v9): %dn", int64(v9))  // 1876219900889841664
    fmt.Printf("float64(v9): %.0fn", v9)     // 1876219900889841664
}

Why all float64 numbers are printed as 1876219900889841664? In javascript this is 1876219900889841700.

Expect same result as in Javascript

js How to get all dates from yearOfWeek or only accept next week dates?

In my app people can enter his work times for next week. So I want to prevent current dates or dates that are later then the next week. I only want to accept next week dates (or dates from a week year).

I found a function in dayjs where I can get the yearOfWeek

const dayjs = require('dayjs');

const weekOfYear = require('dayjs/plugin/weekOfYear');
dayjs.extend(weekOfYear);

const year = dayjs(new Date()).week();

In my app they are also a specific day limit where you can not anymore send your worker times until another week started.

All works but how can I only accept next week dates and not current dates or week that are later then next week ?

I found a way to prevent sending dates at specific time.

I have two variables:

let untilDayNumber = 5; // the number of the day in a week so 5 is friday at friday the user cannot send worker times anymore.
let untilDayHours = 21; // at how much o clock I prevent send the dates so when its friday but under 21 o clock then he can still send his times

I only need a way where I accept only dates from next week or from a specific calendar week.

CurrentCode:

const dayjs = require('dayjs');

const weekOfYear = require('dayjs/plugin/weekOfYear');
dayjs.extend(weekOfYear);

const weekOfYear = dayjs(new Date()).week();

let preventSendDay = 5;
let preventSendHours = 21;

// user worker times
let dates = [new Date(2024, 2, 8), new Date(2024, 2, 9), new Date(2024, 2, 10)];
const today = new Date();

const day = today.getDay() === 0 ? 7 : today.getDay(); // get day number

const hours = today.getHours(); // get day hours

// Now find a solution to accept only next week worker times


// prevent send worker times at specific day
if (
  day > preventSendDay ||
  (day === preventSendDay && hours >= preventSendHours)
) {
  console.log('PREVENT SENDING WORKER TIMES');
}

How to set axios globally in Angular17 app

I had in Vue.js axios config file:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000/api/v1';

so i didnt have to use URL in all the API request across the app.
Now i created axios.ts file in Angular17 project in src folder:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000/api/v1';
export default axios;

But i dont know to globally use it across the whole app, and dont import it in every service file.

i want to change:

const res = await axios.get(http://localhost:8000/api/v1/card);

to

const res = await axios.get('/card');

Read/Write JSON on server on a Next.js project

this is the first time I am asking questions on stackoverflow.

I am working on small projects which build a 10 pages website with next.js, I have experience implementing CRUD between next.js and firebase. This time, I want to put all the static content of website inside some .json files because the content is not that much.

I successfully get the data in .json file by importing the json file, let the page render them.

When I try to build an api in next.js, I did get GET, POST, PUT, DELETE through postman. But I get stuck when I try to write / modify the content in the json file.

that’s what I have try:

src/app/api/content/route.ts:

`import {  GetStaticContent, UpdateProgressBarContent } from "@/app/lib/dataDriver";
import { NextResponse } from "next/server";

export async function GET(req: Request, res: Response) {

try{
const data = GetStaticContent();
return NextResponse.json({message:"GET OK", data}, { status: 200 });
} catch (error) {
return NextResponse.json({ message: "error", error }, { status: 500 });
}
}

export async function PUT(req: Request, res: Response) {
const input = await req.json();
try{
UpdateProgressBarContent(input);
return NextResponse.json({message:"PUT OK", input}, { status: 200 });
} catch (error) {
return NextResponse.json({ message: "error", error }, { status: 500 });
}
}

src/lib/dataDriver.js:

import pageData from '@/app/_json/testing.json';

const fs = require('fs');
const path = require('path');
const dataFilePath = path.join(process.cwd(), '../app/_json/individual.json');
console.log(dataFilePath);

let jsonData = require(dataFilePath);

export function GetStaticContent() {
return pageData.staticContent;
}

export function GetProgressBarContent() {
return pageData.progressBarContent;
}

export function UpdateProgressBarContent({input}) {

    const data = fs.readFileSync(jsonData);
    console.log(data);
    
    console.log(input);
    console.log(input.dataName);
    console.log(input.newValue);
    
    fs.writeFileSync(dataFilePath, JSON.stringify(input, null, 4));
    console.log('Data updated');
    console.log(data);

}`

There is an error of :

`Error: Cannot find module '/Users/[myUserName]/Documents/[myProjectName]/src/app/_json/testing.json'`

But when I copy that path, and run it in the browser, it works and the json content are showing.

Could you please guide me how to make this works?
or Should I placed those JSON on the server first, and then use a url to get it done?
or What I am doing, is it wrong from the start, I must use a database for this?

Range from react-input-range is not responding to handleChange

I’ve created a drum machine app where clicking on keys on the keyboard, keys react and respond with audio. but when I try to change the volume of those sounds they does not change. min and max values should be within [0, 1 range] cause method play() does not allow use another range.

import "react-input-range/lib/css/index.css";
import InputRange from "react-input-range";

function App() {
  const pads = [
    {
      key: "Q",
      id: "Heat-1",
      url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3",
    }
...

  ];
  const [volume, setVolume] = useState(0.2);
  const handleChange = (value) => {
    console.log(value);
    setVolume(value);
  };
  const handlePlay = (e) => {
    for (let i = 0; i < pads.length; i++) {
      if (e.key.toUpperCase() === pads[i].key) {
        const audio = new Audio(pads[i].url);
        audio.play();
        audio.volume = volume;
      }
    }
  };
  useEffect(() => {
    document.addEventListener("keydown", handlePlay);
    return () => {
      document.removeEventListener("keydown", handlePlay);
    };
  }, [pads, volume]);

  return (
    <div>
      <div className="drum-machine">
        {pads.map((pad) => (
          <div key={pad.key} className="drum-pad" id={pad.id}>
            {pad.key}
          </div>
        ))}{" "}
      </div>
      <h5>Power</h5>
      <InputRange
        maxValue={1}
        minValue={0}
        value={volume}
        onChange={handleChange}
      />
    </div>
  );
}

export default App;

Why does React fragment needs a unique key attribute when rendered in a loop

So according to the docs, React fragment does not appear on DOM. It doesn’t inject any elements to the DOM.

But let’s say we want to render elements in a loop whose inside a fragment

elementList.map((eachEl) => <> {<span></span>} </>)

There is a warning in the console “Each child in a list should have a unique “key” prop “. If you assign key to the each element, the warning does not go away.

elementList.map((eachEl) => <> {<span key={uniqeKeyValue} ></span>} </>)

If we assign a key to the fragment, the warning goes away.

So, since React fragment does not inject any elements to the DOM, why does it needs a unique key attribute? It looks like assigning key to the each element should be okay.

Why a “ghost element” that doesn’t even appear and settled on the DOM needs a unique key?

edittext not responsding .onClick (Extendscript)

Why is this not working?

...
var newFolder = inputGroup.add ("group");
var newIFolder = newFolder.add("edittext",[0, 0, 300, 20]);
var addButton =  newFolder.add ("button", undefined, "Add");


var closeButton = window.add ("button", undefined, "Close");

closeButton.onClick = function() {
    window.close();}

addButton.onClick = function() {
    return newIFolder.text;
    window.close();
    alert(newFolder.text);}
...

Nothing happens onClick, the window just remains open.

Perhaps it’s because of the groupings, somehow. I’ll try to move it on top level, while I wait.

Thanks in advance and best regards.

Edit: On top level no change 🙁
Edit2: I’ve tried, but no change 🙁

var addButton =  window.add ("button", undefined, "Add", {name: "ok"});