React grid layout resets local storage when dynamically generated cards

I am dynamically getting data from backend and converting them to cards,
These cards are draggable and also resizable
When I change the layout (say by dragging a card to different location),
my local storage is updated perfectly
When I refresh the page, the layout is changed/resetted,even in local storage

  useEffect(() => {
  fetchCharts();
  }, []);

  // related to react grid layout
  const [state, setState] = useState({
    layouts: JSON.parse(JSON.stringify(originalLayouts)),
  });

  const resetLayout = () => {
    setState({ layouts: {} });
  };

 const onLayoutChange = (layout, layouts) => {
if(!isLoading){

  console.log(layouts)
  saveToLS("layoutsInventory", layouts);
  console.log('Lauyots' ,layouts);
  setState({ layouts });
 }
};

These functions are above component

function getFromLS(key) {
  console.log(key)
  let ls = {};
  if (global.localStorage) {
  try {
  ls = JSON.parse(global.localStorage.getItem("rgl-Inventory")) || {};
 } catch (e) {
  /*Ignore*/
  console.log(e)
 }
}
console.log(ls[key])
return ls[key];
}

//Set to local storage- layout
function saveToLS(key, value) {
if (global.localStorage) {
global.localStorage.setItem(
  "rgl-Inventory",
  JSON.stringify({
    [key]: value,
  })
 );
}
 }

My imports

import { WidthProvider, Responsive } from "react-grid-layout";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";

const ResponsiveReactGridLayout = WidthProvider(Responsive);
const originalLayouts = getFromLS("layoutsInventory") || {};

My localstorage
Local Storage

My local storage when I change the position of one card, therefore layout is changed also in Local storage
When layout is changed

now when I refresh the page it is again changed to first image,which shouldn’t happen

My whole code

import { useEffect, useState } from "react";
import ToastMsg from "../UI/ToastMsg";
import { toast } from "react-toastify";
import NautoChart from "./NautoChart";

import { WidthProvider, Responsive } from "react-grid-layout";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";

const ResponsiveReactGridLayout = WidthProvider(Responsive);
const originalLayouts = getFromLS("layoutsInventory") || {};

const options = {
  maintainAspectRatio: false,
  elements: {},
  layout: {
    autoPadding: true,
  },
  plugins: {
    legend: {
      display: false,
      position: "left",
      labels: {
        usePointStyle: true,
        pointStyle: "circle",
        padding: 16,
      },
    },
  },
};

//Get from local storage- layout
function getFromLS(key) {
  console.log(key)
  let ls = {};
  if (global.localStorage) {
    try {
      ls = JSON.parse(global.localStorage.getItem("rgl-Inventory")) || {};
    } catch (e) {
      /*Ignore*/
      console.log(e)
    }
  }
  console.log(ls[key])
  return ls[key];
}

//Set to local storage- layout
function saveToLS(key, value) {
  if (global.localStorage) {
    global.localStorage.setItem(
      "rgl-Inventory",
      JSON.stringify({
        [key]: value,
      })
    );
  }
}

const ChartDisplay = () => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true)
  const fetchCharts = async () => {
    
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_DOMAIN}/nautobot/charts/chart`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ method: "get" }),
        }
      );

      if (response.ok) {
        const responseData = await response.json();
        setData(responseData.results);
      } else {
        throw new Error(`Failed To fetch, Retry: ${response.status}`);
      }
    } catch (error) {
      const err = error.message || error.Error || error;
      console.error("Error fetching data:", err);
      const errorToast = () => {
        toast.error(<ToastMsg message={err} />, {
          hideProgressBar: true,
          progress: undefined,
        });
      };
      errorToast();
      // You can also set an error state here if needed
    }

    finally{
      setIsLoading(false)
    }
  };

  useEffect(() => {
    fetchCharts();
  }, []);

  // related to react grid layout
  const [state, setState] = useState({
    layouts: JSON.parse(JSON.stringify(originalLayouts)),
  });

  const resetLayout = () => {
    setState({ layouts: {} });
  };

  const onLayoutChange = (layout, layouts) => {
    if(!isLoading){

      console.log(layouts)
      saveToLS("layoutsInventory", layouts);
      console.log('Lauyots' ,layouts);
      setState({ layouts });
    }
  };
  // related to react grid layout

  return (
    <>
      {console.log('Layouts state',state.layouts)}

      <div className='w-full px-4 sm:px-8 bg-red-500'>
        <button onClick={() => resetLayout()}>Reset Layout</button>

        <ResponsiveReactGridLayout
          useCSSTransforms={false}
          draggableHandle=".drag-handle"
          className="layout"
          // margin={[80,80]}
          cols={{ lg: 24, md: 20, sm: 12, xs: 8, xxs: 4 }}
          // containerPadding={{lg:[30,30],}}
          rowHeight={30}
          layouts={state.layouts}
          onLayoutChange={(layout, layouts) => onLayoutChange(layout, layouts)}
        >
          {/* <div className="w-full mxsm:px-2 msm:px-4 sm:px-8 grid grid-cols-2 gap-4"> */}
            {data?.map((el,index) => {
              
              return ( <div
                  key={el.id}
                  // key={index.toString()}
                  className="border border-gray-200  rounded-xl shadow-sm overflow-clip"
                  data-grid={{ w: 10, h: 7, x: 0, y: 0 }}
                >
                  <NautoChart
                    chartData={el.chart}
                    options={options}
                  />
                  
                </div>
              );
            })}
          {/* </div> */}
        </ResponsiveReactGridLayout>
      </div>
    </>
  );
};

export default ChartDisplay;

How can I see whether a JavaScript function is monomorphic?

I’m trying to understand better how V8 optimizes property access with some concrete examples. Is there a way to see in Chromium whether some function uses inline caching, or if it has been deoptimized to be megamorphic? I tried looking in the “Performance” tab of Chrome’s Developer Tools and profiling my code, but I couldn’t find any information about inline caching. Is there any other way?

Why filterinng functions doesnt works corectly?

import { useState } from "react";
import Modal from "./components/compfold/modal";

export default function App() {
  const arr = [
   
  ];
  const [tasks, setTasks] = useState(arr);
  const [selectedOption, setSelectedOption] = useState("");
  const [activeModal, setActiveModal] = useState(false);

  const handleDataFromChild = (inputData) => {
    console.log("Received from child:", inputData);

    setTasks((prevTasks) => [...prevTasks, inputData]);

    console.log(tasks);
  };

  const handleChange = (e) => {
    const value = e.target.value;
    setSelectedOption(value);

    let sortedTasks;

    if (value === "most upvotes") {
      sortedTasks = [...tasks].sort((a, b) => b.votes - a.votes);
    } else if (value === "most comments") {
      sortedTasks = [...tasks].sort((a, b) => b.comments - a.comments);
    } else {
      sortedTasks = tasks;
    }

    setTasks(sortedTasks);
  };

  const filterByTag = (tag, e) => {
    e.preventDefault();
    const completeTasks = arr.filter((item) => item.tag === tag);

    setTasks(completeTasks);
  };

  const handleReset = () => {
    setTasks(tasks);
  };

  return (
    <>
      <div className="container bg-[#F7F8FD] h-screen w-full flex row align-top">
        <div className="column-onebg-[#F7F8FD] h-full w-60">
          <div className="option-cont">
            <ul className="m-4 p-4 bg-white ">
              <li className="cursor-pointer" onClick={handleReset}>
                All
              </li>
              <li
                className="cursor-pointer"
                onClick={(e) => filterByTag("ui", e)}
              >
                UI
              </li>
              <li
                className="cursor-pointer"
                onClick={(e) => filterByTag("ux", e)}
              >
                UX
              </li>
              <li
                className="cursor-pointer"
                onClick={(e) => filterByTag("enchancement", e)}
              >
                Enhancement
              </li>
              <li
                className="cursor-pointer"
                onClick={(e) => filterByTag("bug", e)}
              >
                Bug
              </li>
              <li
                className="cursor-pointer"
                onClick={(e) => filterByTag("feature", e)}
              >
                Feature
              </li>
            </ul>
          </div>
        </div>
        <div className="column-two">
          <div className="topbar flex row w-full p-5 gap-5 bg-[#373F68] rounded-r-lg">
            <div className="sug text-white">
              <p>0 Sugestions</p>
            </div>
            <div className="sort flex row">
              <p className="text-white">sort by:</p>
              <select id="sort" value={selectedOption} onChange={handleChange}>
                <option value="most upvotes">most upvotes</option>
                <option value="least updates">Least updates</option>
                <option value="most comments">Most Comments</option>
                <option value="least comments">Least Comments</option>
              </select>
            </div>
            <button
              className="text-white"
              onClick={() => {
                setActiveModal(true);
              }}
            >
              Add Feedback
            </button>
          </div>

          <div className="tasks-cont">
            {tasks.map((item) => (
              <div key={item.id} className="p-4">
                {item.tittle}, {item.votes}, {item.tag}, Comments:{" "}
                {item.comments}
              </div>
            ))}
          </div>
        </div>
      </div>
      <Modal
        activeModal={activeModal}
        setActiveModal={setActiveModal}
        sendDataToParent={handleDataFromChild}
      />
    </>
  );
}

After adding a new function, I want it to be assigned to a specific tag. however, after adding a new task and filtering the result from the list, they disappear completely.

Why isn’t blob initalized?

I have this part of code which is supposed to create File from Buffer.

    const { buffer } = downloadResult;
    logger.info(buffer);
    const blob = new Blob([buffer], { type: 'image/png' });
    logger.info('fil1', blob);

    const file = new File([blob], fileName);
    logger.info('fil2', file);

    result.image = file;
    logger.info(result.image);

For some reason blob and file constants are empty. This is logger output:

20-09-2023 16:30:03:303 info: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 00 00 00 02 00 08 06 00 00 00 f4 78 d4 fa 00 00 00 04 73 42 49 54 08 08 08 08 7c 08 64 88 00 ... 21314 more bytes>
20-09-2023 16:30:03:303 info: object
20-09-2023 16:30:03:303 info: fil1
20-09-2023 16:30:03:303 info: fil2
20-09-2023 16:30:03:303 info: PersistentFile {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  lastModifiedDate: null,
  filepath: undefined,
  newFilename: undefined,
  originalFilename: undefined,
  mimetype: undefined,
  hashAlgorithm: undefined,
  size: 0,
  _writeStream: null,
  hash: null,
  [Symbol(kCapture)]: false
}

What am I doing wrong?

Fetch Javascript throws Error 404 in console even with a `try…catch` method

I cannot get rid of the error showing in console, even with nested try...catch
Here’s the function :

async function checkFileExists(url) {
    try {
    return await fetch(url)
        .then((response) => {
            if (response.status === 200) { return true; }
            else { return false; }
        })
        .catch(() => { return false; });
    }
    catch (error) {
        return false;
    }
}

There’s also a try...catch at the call of the function

        try {
            const imgLongExists = await checkFileExists(imgLongPath);
            if (imgLongExists) { cardImgLong.src = imgLongPath; }
            else { cardImgLong.src = "img/blank-long.png"; }
        }
        catch (error) {
            cardImgLong.src = "img/blank-long.png";
        }

Intersection Observer: When element is in view stat counter goes up as should but once out of view and back it view – stat counter doesn’t stop

Sorry for another question but this is my first time using intersection observer and it’s working partially. Once the elements are intersecting for the first time the stat counter rises as it should but once they are not intersecting and go back to intersecting the counter goes well beyond the value and doesn’t stop. How can I prevent that from happening?

let statContainer = document.getElementsByClassName("stat-container");

const observer = new IntersectionObserver(stat => {
    stat.forEach(stat => {
        if (stat.isIntersecting) {
            for (var i = 0; i < statContainer.length; i++) {
                let container = statContainer[i];
              
                let circularProgress = container.querySelector(".circular-progress"),
                    progressValue = container.querySelector(".progress-value");
              
                let progressStartValue = 0,
                    progressEndValue = progressValue.textContent,
                    speed = 10;
              
                let progress = setInterval(() => {
                  progressStartValue++;
              
                  progressValue.textContent = `${progressStartValue}%`;
                  circularProgress.style.background = `conic-gradient(#099bf0, #7cbf3d,#00b3cf, #1f58f2, #5618d4 ${progressStartValue * 3.6}deg, #EAEAEC 0deg)`;
              
                  if (progressStartValue == progressEndValue) {
                    clearInterval(progress);
                  }
                }, speed);
              }
        } else {
            console.log("not intersecting")
        }
    })
    
});

observer.observe(statContainer[0]);
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
body{
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #7d2ae8;
}
.container{
    display: flex;
    width: 420px;
    padding: 50px 0;
    border-radius: 8px;
    background: #fff;
    row-gap: 30px;
    flex-direction: column;
    align-items: center;
}
.circular-progress{
    position: relative;
    height: 250px;
    width: 250px;
    border-radius: 50%;
    background: conic-gradient(#7d2ae8 3.6deg, #ededed 0deg);
    display: flex;
    align-items: center;
    justify-content: center;
}
.circular-progress::before{
    content: "";
    position: absolute;
    height: 210px;
    width: 210px;
    border-radius: 50%;
    background-color: #fff;
}
.progress-value{
    position: relative;
    font-size: 40px;
    font-weight: 600;
    color: #7d2ae8;
}
.text{
    font-size: 30px;
    font-weight: 500;
    color: #606060;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>

    <link rel="stylesheet" href="./css/stylesheet.css">
</head>
<body>

    <div class="spacer"></div>

    <div class="stat-container">
        <div class="circular-progress">
            <span class="progress-value">
                55
            </span>
        </div>
        
        <span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.</span>
    </div>

    <div class="stat-container">
        <div class="circular-progress">
            <span class="progress-value">
                70
            </span>
        </div>
        
        <span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.</span>
    </div>

    <div class="stat-container">
        <div class="circular-progress">
            <span class="progress-value">
                67
            </span>
        </div>
        
        <span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.</span>
    </div>

    <!-- JavaScript -->
    <script src="./js/script.js"></script>
</body>
</html>

intl-messageformat: Ignore escape sequences for message syntax chars

is there any way change the behaviour for parsing quotes when using Intl MessageFormat?

This section in the docs says:

Supports escape sequences for message syntax chars, e.g.: “‘{foo}'” will output: “{foo}” in the formatted output instead of interpreting it as a foo argument.


Default behaviour

const msg = new IntlMessageFormat("Email: '{email}'").format({email: "[email protected]"}) 
// -> msg: "Email: {email}"

Desired behaviour

const msg = new IntlMessageFormat("Email: '{email}'").format({email: "[email protected]"}) 
// -> msg: "Email: [email protected]"

How can I accomplish the desired behaviour? Thanks.

Why in React Big Calender “onDropEvent” handler, “event” prop is missing “id” type in it (using Typescript)

“onEventDrop” handler, event prop is missing its “id” type, even though it exists in “event” data!!

    const handleResizeEvent:withDragAndDropProps["onEventDrop"] = (data) => {
        const {end, start, event} = data;
        console.log(event?.id, "its here but typescript saying its missing")
    }

though i can do “stuff” with that “id” from this “event” dataset, but typescript is still giving me “Property ‘id’ does not exist on type ‘Event'”

what am i missing here? thanks and happy coding to all 🙂

i tried to use “EventInteractionArgs” for “data” props but still same “typescript” error is showing up in “vscode”

i can see that “id” value is in there
a screenshot with console in view

How to correctly encodeURIComponent?

In my work I need to use encodeURIComponent, but it’s not in the correct structure, and the access to the endpoint doesn’t work correctly.

In the images below you can see the differences between the structures of header of the current application, where theencoded is being done correctly. And my code, where the encoded is not being done correctly. I created a function to do this, but it’s not working. Can you tell me what I’m doing wrong?

Here’s my code I put into codesandbox.io

  const BASE_URL = "";

  function encodeHeaders(headers) {
    let encodedHeaders = "";

    for (const key in headers) {
      encodedHeaders += encodeURIComponent(key + ": " + headers[key]) + "%0A";
    }

    return encodedHeaders;
  }

  const headers = {
    Connection: "close",
    "Content-Type": "application/json",
    "X-EES-AUTH-CLIENT-ID": "o75j23m4c2m3e411sb7z",
    "X-EES-AUTH-HASH":
      "e782225331d2839774aac84eab2762a9c8059cfc7433af8f178138ab426fbfbf",
    accept: "application/json"
  };

  const requestData = {
    code: "ee",
    branch: "119",
    till: "7",
    serial: "912347",
    url: "https://resources.sandbox",
    method: "GET",
    header: encodeHeaders(headers)
  };

  /**
   * Example of how I am using the application in a real test
   */
  function getTestService() {
    return axios
      .post(BASE_URL, requestData, {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
        }
      })
      .then((response) => {
        return response.data;
      });
  }

Here’s what I get vs what I expect:

What I get (before and after encoded)

header: Connection%3A%20close%0AContent-Type%3A%20application%2Fjson%0AX-EES-AUTH-CLIENT-ID%3A%20o75j23m4c2m3e411sb7z%0AX-EES-AUTH-HASH%3A%20e782225331d2839774aac84eab2762a9c8059cfc7433af8f178138ab426fbfbf%0Aaccept%3A%20application%2Fjson%0A

Connection%253A%2520close%250AContent-Type%253A%2520application%252Fjson%250AX-EES-AUTH-CLIENT-ID%253A%2520o75j23m4c2m3e411sb7z%250AX-EES-AUTH-HASH%253A%2520e782225331d2839774aac84eab2762a9c8059cfc7433af8f178138ab426fbfbf%250Aaccept%253A%2520application%252Fjson%250A
What I expect (before and after encoded)

header: Connection: close
Content-Type: application/json
X-EES-AUTH-CLIENT-ID: o75j23m4c2m3e411sb7z
X-EES-AUTH-HASH: e782225331d2839774aac84eab2762a9c8059cfc7433af8f178138ab426fbfbf
accept: application/json

Connection%3A+close%0AContent-Type%3A+application%2Fjson%0AX-EES-AUTH-CLIENT-ID%3A+o75j23m4c2m3e411sb7z%0AX-EES-AUTH-HASH%3A+e782225331d2839774aac84eab2762a9c8059cfc7433af8f178138ab426fbfbf%0Aaccept%3A+application%2Fjson

enter image description here

It is possible to notice the difference between the structures of each of the headers. Before and after encoded.

enter image description here

Can’t get response from Zendesk ticket API with JavaScript fetch

I’m trying to create an HTML form which creates a ticket in Zendesk. The form will also include a file upload.
Right now I’m able to create the ticket with the API, but I can’t get the response from the API call. I need the response to get the ticket id from the created ticket. I can use this id the attach the uploaded file to the ticket.
But like I said, I can’t retrieve the response.

Code:

function createTicket() {      
    var id;
    var easyWalker = $("#choose_product option:selected").html();
    var batchNumber = document.getElementById("batch_number").value;
    var color = document.getElementById("color").value;
    var firstName = document.getElementById("first_name").value;
    var lastName = document.getElementById("last_name").value;
    var email = document.getElementById("email").value;
    var phone = document.getElementById("phone").value;
  
    console.log("creating ticket");

    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Authorization", "Basic " + auth);
    myHeaders.append("Cookie", "__cfruid=f6f220be875e5825ba2ea5650a7a58d04ceb1299-1695207433; _zendesk_cookie=BAhJIhl7ImRldmljZV90b2tlbnMiOnt9fQY6BkVU--0bf2100788cb010d0183feca16aaf88ccaf719ca");
    
    var raw = JSON.stringify({
            "ticket": {
                "subject": "New Easywalker Warranty Registry from " + firstName + " " + lastName,
                "description": 
                  "Product: " + easyWalker + "n" +
                  "Batch Number: " + batchNumber + "n" +
                  "Color: " + color + "n" +
                  "Name: " + firstName + " " + lastName + "n" +
                  "Email: " + email + "n" +
                  "Phone Number: " + phone,
                "requester": {
                  "name": firstName + " " + lastName,
                  "email": email
                }
            }
        });
    
    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      redirect: 'follow'
    };
    
    fetch("https://easywalkersupport.zendesk.com/api/v2/tickets", requestOptions)
      .then(response => id = response)
      .then(result => console.log(result))
      .catch(error => console.log('error', error));

    return id;
}

I know that response isn’t the id, but I don’t know what property I need to access to do so, because I can’t see the result. Previously I used console.log(result) but nothing was displayed in the console.

Could someone help me with a solution and an example of an implementation of the given solution?

Thanks in advance!

Ivan

Refresh token function

Good morning. This is my App component in my React app:

What i would like to do is write a function refreshToken so that even when the token expires, the user can stay logged in and everything keeps working smoothly, but i don’t know where to start from. can anyone help me out writing the function?

import React, { useEffect, useState } from 'react';
import { Route, Routes} from 'react-router-dom';
import LandingPage from './components/LandingPage';
import UserDashboard from './components/UserDashboard';
import PlaylistPage from './components/PlaylistPage';
import ConnectionError from './components/ConnectionError';
import 'react-notifications/lib/notifications.css';
import axios from 'axios';

function App() {
  const [token, setToken] = useState('');
  const [profile, setProfile] = useState({});
  const [playlists, setPlaylists] = useState([]);
  const [isOnline, setIsOnline] = useState(true);


  useEffect(() => {
    const handleOnlineStatusChange = () => {
      setIsOnline(window.navigator.onLine);
    };
  
    window.addEventListener('online', handleOnlineStatusChange);
    window.addEventListener('offline', handleOnlineStatusChange);
  
    return () => {
      window.removeEventListener('online', handleOnlineStatusChange);
      window.removeEventListener('offline', handleOnlineStatusChange);
    };
  }, []);
  

    // funzione per gestire l'autenticazione
    const handleAuthorization = () => {
      const clientId = 'f789423275064f74889fc3d48e4d85fe';
      const redirectUri = 'http://localhost:3000';
      const scopes = ['user-library-read', 'playlist-read-private', 'playlist-modify-private', 'playlist-modify-public', 'playlist-read-collaborative'];
      const authorizationURL = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&redirect_uri=${encodeURIComponent(
        redirectUri
      )}&scope=${scopes.join('%20')}`;
    
      // Redirect for authorization
      window.location.href = authorizationURL;
    };
    

useEffect(() => {
  const fetchData = async () => {
    const hash = window.location.hash;
    const tokenParam = new URLSearchParams(hash.substring(1)).get('access_token');

    if (tokenParam) {
      // Token is present in the URL
      const newToken = tokenParam;
      window.localStorage.setItem('token', newToken);
      setToken(newToken);

      // Redirect to the dashboard
      window.location.href = '/dashboard';
    } else {
      // Token is not present in the URL, handle token expiration or other logic here
      const storedToken = window.localStorage.getItem('token');

      if (storedToken) {
        // Token is stored locally, you can set it and perform necessary actions
        setToken(storedToken);

        // Fetch user data and playlists here
        try {
          const response = await axios.get('https://api.spotify.com/v1/me', {
            headers: {
              Authorization: `Bearer ${storedToken}`,
            },
          });

          const { data } = response;
          setProfile(data);

          // Fetch playlists
          try {
            const playlistsResponse = await axios.get('https://api.spotify.com/v1/me/playlists', {
              headers: {
                Authorization: `Bearer ${storedToken}`,
              },
              params: {
                limit: 50,
              },
            });

            const { data: playlistsData } = playlistsResponse;
            setPlaylists(playlistsData.items);
            console.log(playlistsData.items);
          } catch (error) {
            console.error('Error fetching playlists:', error);
          }
        } catch (error) {
          console.error('Error fetching user data:', error);
        }
      }
    }
  };

  fetchData();


}, []);

 
  const logout = () => {
    setToken('');
    setProfile({});
    setPlaylists([]);
    window.localStorage.removeItem('token');
    // Redirect the user to the home page after logging out
    window.location.assign('http://localhost:3000');
  };



  return (
    <div>
    {isOnline ? (
      <Routes>
        <Route path="/" element={<LandingPage handleAuthorization={handleAuthorization} />} />
        <Route path="/dashboard" element={<UserDashboard profile={profile} playlists={playlists} logout={logout} />} />
        <Route path="/playlist/:id" element={<PlaylistPage />} />
      </Routes>
    ) : (
      <ConnectionError />
    )}
  </div>
  );
}

export default App;

i’ve tried writing functions myself but they did not work

How to Use Cypress and Gherkin to automate one scenario with four different users using fixture?

I am using Cypress and Gherking but I have some scenarios where I have to execute it with more than one user.

I don’t want to use the Scenario Outline for it because I would have to create a table for each scenario. My user data are at a fixture file, but I don’t know how to execute for each user the scenarios.

Is there a way to set the user and execute the scenario once, but for all the 4 users?

My fixture file:

{   
  "standard":{  
      "name": "The site should work as expected for this user",
      "user_name": "standard_user",
      "password": "secret_sauce"
    },

    "locked":{  
      "name": "User is locked out and should not be able to log in.",
      "user_name": "locked_out_user",
      "password": "secret_sauce"
    },

    "problem":{  
      "name": "Images are not loading for this user.",
      "user_name": "problem_user",
      "password": "secret_sauce"
    },

    "performance":{  
      "name": "This user has high loading times. Does the site still work as expected?",
      "user_name": "performance_glitch_user",
      "password": "secret_sauce"
    }
}

ShopList.feature example:

 Scenario: Validate Add to cart counter for each user
        Given the user log in into the application
        When he adds products to the cart
        Then the amount added should be the same as the counter
        And the cart should contains the added itens

I found a solution using .foreach() but for the it() function

users.forEach((user) => {
  it(`Log in with ${user.username}`, () => {
    // Visit the login page and enter login credentials for each user
    cy.visit('/login');
    cy.get('#username').type(user.username);
    cy.get('#password').type(user.password);
    cy.get('#login-button').click();

I want the same result but integrating it with gherkin.

Migrate and convert project from jQuery to React [closed]

I create a small project in HTML, CSS, jQuery that change images based on mouse movement and I want to convert this jQuery code into React code.

Now I am trying to convert this code into React code I have tried but I am not understanding how can I do this. I have tried some online code converter tools but it’s not working. Help me to convert this code into React code. Code will be attached in link

Working Example https://replit.com/@vivektarsariya/RotatingHead?v=1

how to save data in separate file in google sheet in react natvie

I use the best sheet API to save the data into the Google sheet. it saves my data to Google Sheets but it duplicates data again and again. now I want to create a new file every time the user wants to save this data in a separate file in the same Google sheet. but I can not do this in the bedsheet API. so how can this with bestsheet API?

const url = 'https://sheet.best/api/sheets/69042d86-72ec-4c78-8400-67a9bd4cf766?fileName=`${fileName}`';

    const config = {
        headers: {
            'Content-Type': 'application/json',
        },
    };

    axios
        .post(url, formattedTrans, config)
        .then(response => {
            console.log('Response ------------------------------------>>>', response);
            dispatch(changeLoadingStatus());
            if (response) openGoogleSheetsLink();
        })
        .catch(error => {
            dispatch(changeLoadingStatus());
            if (error.response) {
                console.log('Response Data:', error.response.data);
                Toast.show({
                    type: 'error',
                    text1: 'Server Error',
                    text2: 'Server Error Request failed!'
                });
            }
        });

enter image description here

let’s see the above image my data is only saved in sheet 1 and duplicates many times. but I want to save data in separate files i.e. sheet1, sheet2, and so on. I want the sheets to be created while saving the data.