How can I cancel axios request by token?

I’m trying to cancel axios request by token in useEffect:

// http-request.js

export const cancelelationSource = axios.CancelToken.source();

export const get = endpoint => {
  return axios.get(endpoint, {
    headers: { ...headers },
    timeout: 20000,
    cancelToken: cancelelationSource.token
  })
    .then(response => response.data)
    .catch(e => {
      console.log(e);
    });
}

then in component:

import { get, cancelelationSource } from './http-request';

const About = () => {
  useEffect(() => {
    get('http://localhost:3001/test2').then(data => console.log(data))
  }, []);
  return (
    <h1>About</h1>
  )
}

const App = () => {
  useEffect(() => {
    get('http://localhost:3001/test').then(data => console.log(data))

    return () => cancelelationSource.cancel();
  }, []);

  return (
    <div>
      <Link to="/about">About</Link>
    </div>
  )
}

render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="/about" element={<About />} />
    </Routes>
  </BrowserRouter>,
  document.getElementById('root')
);

request cancelation works well when I click on the About link. but second API fetch doesn’t work in component <About />

I think axios cancels all requests… I want cancel previous requests but new request should be able to fetch data after change pages or redirect!

Regex appears correct but after passing to javascript replaceAll function it doesnt remove digits in the beggining as expected

I have a regex that I run on a text to remove digits before a “.” as well as some random characters that may appear after it. This regex matches everything i need it to match which I confirmed in regex101.com. However when I pass it to my javascript function as a parameter to the replaceAll() function, the text returned still has some numbers at the end. After countless hours searching online, i still don’t understand why this is happening. Does anyone know the cause?

Regex entered in regex101.com

(^[+-]?d+(.|s|-|)|(s-.)|(s.)?)+(^dd|[^u4E00-u9FA5|a-zA-Z|/:«»|0-9|();n]|d*[.])

Sample text:

11.君曰
1100.君曰
11.君曰
情奴(新版)
我在未来等着你
11.君曰
11.君曰
11678.君曰
11- -.情海孤舟
11 爱 .情海孤舟

Current output from my js function

updatedText = updatedText.replaceAll(/(^[+-]?d+(.|s|-|)|(s-.)|(s.)?)+(^dd|[^u4E00-u9FA5|a-zA-Z|/:«»|0-9|();n]|d*[.])/g, "");

output:
君曰
君曰
君曰
情奴(新版)
我在未来等着你
君曰
君曰
君曰
11情海孤舟
11爱情海孤舟

Any help in explaining why the 11’s are still in the output would be awesome! Thanks in advance.

blank map with gray background while using react-map-gl in production build (even after trying all 3 solutions from mapbox official)

I am not able to display map properly in production, while using react-map-gl in create-react-app. App is working fine on localhost but it throws errors in the console while running in production.
I have tried all the 3 solutions mentioned in official mapbox docs https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling

I first tried these solutions one by one separately, and then all 3 solutions simultaneously, but none of these 4 attempts worked.

I have attached the screenshot of console errors below along with live URL of my production site and github code.

Live URL: https://parking-app-fyp.vercel.app
github code: https://github.com/iAmZubair00/parking-app-fyp

screenshot of console error

I am also adding 3 pieces of code related to 3 solutions for your convenience

import mapboxgl from "mapbox-gl";
// eslint-disable-next-line import/no-webpack-loader-syntax
import MapboxWorker from "worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker";
mapboxgl.workerClass = MapboxWorker.default;
module.exports = {
  babel: {
    loaderOptions: {
      ignore: ["./node_modules/mapbox-gl/dist/mapbox-gl.js"],
    },
  },
};
"browserslist": {
    "production": [
      ">0.2%, not dead, not ie 11, not chrome < 51, not safari < 10",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }

How to reformat json in java script [closed]

json that i get from api

[
  {
    "value": "45",
    "timestamp": "2022-01-21T00:00:12.847",
    "id": "cabc6d20-f305-4a1c-888c-dca2043a06ba",
    "ru": "R401",
    "area": "area-1",
    "unit": "33",
    "equipment": "radio",
  },
]

what i want

[
 {
   "id": "946362d4-5e65-421f-8669-c89fa37bb6e7",
   "equipment": "radio",
   "area": "area-1",
   "value": "45",
  },
]

what i want is the order is change, and only pick some key.

thanks for help

Kibana not loading due to unsafe script

I have upgraded my elastic / kibana stack from 7.12.1 to 7.16.2

Unfortunately and despite the fact that elasticsearch is now healthy, kibana is not loading due to a js error:

login:1 Refused to execute script from 'https://my-kibana.com/login?next=%2F39457%2Fbundles%2Fplugin%2Fdata%2Fdata.plugin.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

enter image description here

(there are other errors like this as well)

Any suggestions?

Declare variable inside array’s element in javascript

Does anyone can explain why this code works in javascript ?

let people = [
  "Jeremy",
  "Male",
  (address = [(domicile = [{ province: "jakarta", city: "jakpus" }])]),
  (origin = [{ provinceOrigin: "Lampung", cityOrigin: "Bandar Lampung" }]),
];
console.log(address); //[ [ { province: 'jakarta', city: 'jakpus' } ] ]

does this code declare a variable inside array’s element ? but why i cannot declare the variable using let, const, or var ?

Vue.js and javascript, how should I append the correct string to my URL?

I made a website.

I currently have a form and a link next to the form. When the user clicks on the link, whatever is typed in that form will be added to the url path of /funpage/, and become the new URL path. So for example, If the user types something like /hey/hi then clicks on the link. The link will take the user to a URL like /funpage/hey/hi. Another example, Is if the user types something like /hellooy/hi/hey/whatsup/hi then clicks on the link. The link will take the user to a URL like /funpage/hellooy/hi/hey/whatsup/hi.

The issue is that my Vue.js application with vue router, will think that the user is going to a new webpage, because the user inputted backslashes that get added to the URL and act like it is a whole new path.

My solution is to write a regex like ///g and use the replace function in Javascript, for the user’s input into the form, which gets rid of any backslash characters. So when the user types something like /hey/hi and clicks on the link, it will just take them to /funpage/heyhi which is what I want.

However I am sure that there are more characters that you don’t want to be entered into a URL, that I know the user could input and would break it. I know about encodeURIComponent but this seems to be only used If you want to purposely add query params.

Does someone possibly have a regex better than ///g to escape all characters that shouldn’t be in a URL? or a better solution perhaps.

Thank you!

Cannot read properties of undefined (reading ‘fetch’) on guild.members.fetch()

I am working on setting a script that will cycle thorough all the members in a guild without using the cache system. I am getting an issue where when I use guild.members.fetch() it treats guild.members as undefined. I know it isn’t because I am currently logging guild.members and it is giving me a GuildMemberManager object. I don’t understand when once I use fetch() on it, it is suddenly being viewed as undefined.
Here is a screenshot of the entire error message

function addMissingJsons(message, bot) {
    bot.guilds.fetch("id").then(guild => {
        console.log(guild.members);
        guild.memebers.fetch().then(members => {
            console.log(members);
        });
    });
}

Infinite Scroll Component not showing fetching items while using React Hooks

I’m doing an instant search functionality for food recipes and want to implement Infinite Scroll Component. What I want is to present a search bar as beginning, with no recipes show at all, then when user starts to type letter, it will fetch and show 8 items from data fetching from API, and when scroll down at bottom page it will continue fetch and show the next 8 items.

I’m following instruction from this link, but I encounter two issues:

  • If I set initial useState follow the instruction, it shows 8 empty placeholder (no data)

  • If I scroll down, it will fetch and show the next 8 empty placeholder with no data

If I set initial useState as empty array [], it works fine to fetch and show every placeholder with data in each, so what I understand about this maybe is the code Array.from(Array(8).keys(), n => n + 1) in useState and Array.from(Array(8).keys(), n => n + prevState.length + 1) in function fetchMoreListItems() are not relevant to my case.

My question is how to implement the right code so it can fetch the right data in number of object I want to, so it does with the scroll bar when I scroll down as well. Thank you Everyone!

Here’s my demo: gif

Here’s my code:

// Recipes.js

import React, { useState, useEffect } from "react"
import Axios from "axios"
import RecipeCard from "../components/RecipeCard"
import SearchBar from "../components/SearchBar"
import "../style/Recipes.css"

export default function Recipes() {
  
  const [isLoading, setIsLoading] = useState(false)
  const [query, setQuery] = useState("")
  const [recipes, setRecipes] = useState(Array.from(Array(8).keys(), n => n + 1))
  const [isFetching, setIsFetching] = useState(false)

  const url = `https://www.themealdb.com/api/json/v1/1/search.php?s=${query}`
    
    // function to search for the recipes when enter `search button`
    const searchRecipes = async () => {
      if (query !== "") {
        setIsLoading(true)
        const result = await Axios.get(url)
        console.log(result)
        setRecipes(result.data.meals)
        setQuery("")
        setIsLoading(false)
      } 
    }

    // do instant search when start typing any of letters
    useEffect(async () => {
      if (query !== "") {
        const result = await Axios.get(url)
        console.log(result);
        setRecipes(result.data.meals)
      }
    }, [query])

    // handle handleScroll
    useEffect(() => {
      window.addEventListener('scroll', handleScroll);
      return () => window.removeEventListener('scroll', handleScroll);
    }, [])

    function handleScroll() {
      if (window.innerHeight + document.documentElement.scrollTop + 1 >= document.documentElement.offsetHeight) return
      setIsFetching(true)
    }

    useEffect(() => {
      if (!isFetching) return
      fetchMoreListItems()
    }, [isFetching])

    function fetchMoreListItems() {
      setTimeout(() => {
        setRecipes(prevState => ([...prevState, ...Array.from(Array(8).keys(), n => n + prevState.length + 1)]))
        setIsFetching(false)
      }, 2000);
    }

    const onChange = async e => {
      setQuery(e.target.value)
    }

    const handleSubmit = e => {
        e.preventDefault()
        searchRecipes()
    }

    const clearInput = () => {
      setRecipes([])
      setQuery("")
    }

    return (
        <div className="recipes">
            <div className="search-box">
              <h1>Recipe App</h1>
              <SearchBar
                  handleSubmit={handleSubmit}
                  value={query}
                  name="name"
                  onChange={onChange}
                  isLoading={isLoading}
              />
              {
                query.length !== 0 && 
                  <div className="close-icon" onClick={clearInput}>
                    <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"></path></svg>
                  </div>
              }
              <div className="search-result">
                {
                  recipes && query !== "" &&
                    recipes.slice(0, 5).map((val) => {
                      return (
                        <a className="search-item" href={val.strSource} target="_blank" rel="noopener noreferrer">
                          <p>{val.strMeal}</p>
                        </a>
                      )
                    })
                }
              </div>
            </div>
            <div className="recipes-container">
              {
                recipes && query !== null ?
                  recipes.map((recipe) => (
                      <RecipeCard 
                          key={recipe.idMeal}
                          recipe={recipe}
                      />
                  ))
                  : "We're sorry! No recipe found."
              }
            </div>
            {isFetching && 'Fetching more recipes...'}
        </div>
    )
}

TypeError: sentimentCurrent.map is not a function?

Trying to write a unit test for the below function.

I’m getting an error of

TypeError: sentimentCurrent.map is not a function

      65 |     console.log("sentimentData:",sentimentCurrent,typeof sentimentCurrent);
      66 | 
    > 67 |     sentimentCurrent.map(function (k, num) {
         |                      ^
      68 |       let dateCreated = new Date(k.created * 1000);
      69 | 
      70 |       DataInput.push({

The actual function is below, it takes in raw data and then prepares it to be used in a linegraph essentially.

export default function generateLineGraphPointsSentiment(
  sentimentData
) {
  console.log("sentimentData:",sentimentData,typeof sentimentData);
  if (sentimentData !=null) {
  const DataInput = [];

  Object.keys(sentimentData).map(function (key, item) {
    var sentimentCurrent = sentimentData[key];
    console.log("sentimentData:",sentimentCurrent,typeof sentimentCurrent);

    sentimentCurrent.map(function (k, num) {
      let dateCreated = new Date(k.created * 1000);

      DataInput.push({
        created: dateCreated,
        sentiment: k.sentiment,
        magnitude: k.magnitude,
        date: k.createdDay,
      });
    });

    // {created: 1601820360, sentiment: -0.1, magnitude: 0.1, createdDay: "2020-10-05"}
  });

The test case is as follows,

import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import generateLineGraphPointsSentiment from './generateGraphPointsAnalysis';

const SentimentData = [
  {
    id: 96452,
    user_id: 'asdasd',
    sentiment: -0.1,
    magnitude: 1,
    created: 1629535060,
    createdDay: '2021-08-21',
  },
  {
    id: 96453,
    user_id: 'asdasd',
    sentiment: 1,
    magnitude: 1,
    created: 1629535063,
    createdDay: '2021-08-21',
  },
];

// const setSelectedDate = jest.fn();

describe('Generates Graph Points Sentiment', () => {
  it('should show loader for the LineGraphs graph if no data is present', () => {
    generateSentimentLineGraph = generateLineGraphPointsSentiment(SentimentData);
    console.log(generateSentimentLineGraph,SentimentData,typeof SentimentData);

    expect(generateSentimentLineGraph).toHaveReturned();
  });
});

Any ideas on what is wrong with my code? It works in dev currently, not sure why it’s failing this test now? I think it has something to do with either the type of data being processed, or how I’m using the map functions. Perhaps I can simplify the first map function?

Why is this user id not coming out of req.user;

This is my code for getting user info

router.post("/getuser", fetchuser, async (req, res) => {
  try {
    userId = req.user.id;
    const user = await User.findById(userId).select("-password");
    res.send(user);
  } catch (error) {
    console.error(error.message);
    res.status(500).send("Internal Server Error");
  }
});

and this is the code for middleware fetchuser

const fetchuser = async (req, res, next) => {
const token = req.header('auth-token');
if (!token) {
    res.status(401).send({ error: "Please authenticate using a valid token" })
}
try {
    const data = jwt.verify(token, process.env.SECRET);
    console.log(data);
    req.user = data.user;
    next();
} catch (error) {
    res.status(401).send({ error: "Please authenticate using a valid token" })
}
};

I am getting the user id in console.log but when I try to get the user id in the router.post then I am not able to get the user Info.
Here is the result I am getting.

Server is running on port 5000
Connected to database
{ id: '61e98c45a9d8818292b38505', iat: 1642743501 }
Cannot read properties of undefined (reading 'id')

Please can anyone tell me what is wrong with this?