Only replace first match with .replace

I have a function that looks at a string of content & array of documents and finds any matches, then the user can accept or reject that match (another function). When the user accepts this match, see acceptLink function below, then I would like it to replace the first match and not all matches.

Example Content: “The first time I went home was when I went to see my dog at home.”

Example Array: {name: ‘Home’, link: ‘https://www.home.com/’}

Expected output: “The first time I went < a class=”newLink” href=https://www.home.com/>Home< / a > was when I went to see my dog at home.”

const acceptLink = (a) => {
      var reg = new RegExp('('+a.name+')', 'gi');
      const aTag = '<a class="newLink"  href=' + a.link + '>' + a.name + '</a>'
      setContent(content.replace(reg, aTag));
      const replaceContent = content.replace(reg,aTag)
      const filtered = allLinks.filter(obj => {
      return obj.name !== a.name;
  });

Have I missed something here?

Search by more than one tag in Rawg.io

I am currently developing an application that matches the user with a list of games based in their preferences (I’m running a personality test that returns a string of keywords). My API call looks like this:

 let API_URL = `https://api.rawg.io/api/games?key=XXXXX`;
    fetch(
          `${
            API_URL + `&tags=action,cooperative,farm&page_size=20&page=1`
          }`
        )

I would be expecting the results to include the tags action, cooperative and farm; but, instead, I get a list of results that include just one of them. Myself and teachers/relatives have been investigating through the API docs to see if there is a way to force the query parameters to be concatenated, but no luck so far.

Does anyone have a clue about if this is possible? I’m going to get in touch with Rawg.io’s team as well and post if I get an answer from them.

P.S. Any other gaming database with this possibility would also be happily appreciated!

catching an error or exception thrown from a dynamically appended script element – possible?

I want to stop script execution in a dynamically appended script (as in include_guard) by throwing an error from the appended file. Then I want to catch this error from the file that did the “appending” (as in “making things clean”).

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>pickle</title>
    </head>
    <body>
        <script type="text/javascript">
            var de = document.createElement("script");
            de.src = "file.js";
            
            document.head.appendChild(de);
        </script>
    </body>
</html>

file.js

throw new Error("blabla");

How can I catch the error thrown ?

Something like this doesn’t catch anything:

var de = document.createElement("script");
de.src = "file.js";
try {
    document.head.appendChild(de);
}
catch(e) {
     console.log("got it");
}

I also tried setting an error listener to the window object, which does receive error notification, but the error is not caught.

PWA cache version problem when switching to SPA

I switched from PWA to SPA ( because of caching problems which I cannot resolve right now and im sure just SPA build will be fine )

So basically I changed my app from PWA to SPA hosted on netlify ( so no service workers and workbox files anymore in the static folder )

The problem is that users that have the previous PWA cached app now cannot see the changes
( because it is cached ) so how exactly is this kind of problem resolved

Paste value on react-imask using react hook form

I have a question about using react-imask using react-hook-form.

When I use the input with this configuration below, it works when I type the values, but it doesn’t work when I copy and paste the values, or use the browser history. It seems that the input only takes the value in the blur (leaving the component).

I’ve tried looking through the settings and haven’t found one that works. (on question marks below)

I provided some code sandbox (https://codesandbox.io/s/awesome-hooks-5i0r9d?file=/src/App.tsx)

I thoughts the problem was in the ref, when I just typed the value, that problem won’t appear

how to stop firing a keyDown event that are being called multiple times after one click

window.addEventListener("keydown",(e)=>
  {
    // if(renderBall){    console.log(e.key)
 
   if(e.key=="ArrowLeft")
   {
     setBallPosition({
      ...ballPosition,
      left:(parseInt(ballPosition.left)-5)+"px"  
     })
   }
  //  arrow up
   else if(e.key=="ArrowUp")
   {
    setBallPosition({
      ...ballPosition,
      top:(parseInt(ballPosition.top)-5)+"px" 
   })
    
   }
  //  arrow right
   else if(e.key=="ArrowRight")
   {
    setBallPosition({
      ...ballPosition,
      left:(parseInt(ballPosition.left)+5)+"px" 
   })
   }
  //  arrow down
  if(e.key=="ArrowDown")
  {
    setBallPosition({
      ...ballPosition,
      top:(parseInt(ballPosition.top)+5)+"px" 
   })
  }

  })

output//

enter image description here

here what the problem is naa when i press arrowUp or ArrorDown key then it fires more than 1 times inteadof single time please help me to solve this issue

JavaScript, CryptoJS is not defined?

I’m trying to run the following simple JS code in multiple websites but all throw same error:

var _finalScore = 9; // Final Score
var _tapCount = 3; // Clicks

_tapCount *= 73;

var key = CryptoJS.enc.Utf8.parse('4512631236589784');
var iv = CryptoJS.enc.Utf8.parse('4512631236589784');

console.log(CryptoJS.AES.encrypt(_finalScore.toString(), key, { iv: iv }).toString())
console.log(CryptoJS.AES.encrypt(_tapCount.toString()))

which is:

    var key = CryptoJS.enc.Utf8.parse('4512631236589784');
          ^

ReferenceError: CryptoJS is not defined
    at Object.<anonymous> (/tmp/YA2n3rCQMJ.js:6:11)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Why is that? How can I fix it
I didn’t find any special command to include CryptoJS…

Express backend server not serving all files in react front end production environment but works locally

I have a project using a node js express back-end (run on port 5000) and a ReactJS front end (run on port 3000) in the same project. I am able to run these projects a the same time locally with no issues (using npm start for client and nodemon index.js for server). I am also able to use ‘npm run build’ and serve the static files on http://localhost:3000 with no issues in the production build.

However, when I publish these changes to Azure via the ‘Azure app services” extension in VS Code – I am able to authenticate the user upon login and then only the home directory works correctly. If I try to access another page, I get a 401 unauthorized error and I am not sure why.

Project file structure:

 - MyApp:
   - .vscode
   - Client:
      - build
         - static
            - css
            - js
         - index.html
      - node_modules
      - public
      - src
      - package.json
      - package-lock.json
   - config
   - controllers
   - middleware
   - models
   - index.js
   - package.json
   - package-lock.json

Client–>src–>App.js (client side routes)

function App() {
  return (
    <Routes>
      
      <Route path="/" element={<Layout />}>
        {/* Public routes*/}
        <Route exact path='Login' element={<Login/>}  />
        <Route path="unauthorized" element={<Unauthorized />} />
        <Route path="invalidinvite" element={<InvalidInvite />} />
        <Route path='Application' element={<Application />}  />
        

        {/* Protected routes*/}

        <Route element={ <PersistLogin /> }>
          <Route element={<RequireAuth allowedRoles={[1, 2]}/>}> 
            <Route exact path="/" element={<Invite/>} />
          </Route>

          <Route element={<RequireAuth allowedRoles={[1, 2]}/>}> 
            <Route exact path='Submitted' element={<Submitted/>} />
          </Route>

          <Route element={<RequireAuth allowedRoles={[1, 3]}/>}> 
            <Route exact path='Approved' element={<Approved/>} />
          </Route>
        </Route>

        {/* Catch all*/}
        <Route path="*" element={Error} />
      </Route>
    </Routes>
  );
}

Client–>src–>index.js:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <AuthProvider>
        <Routes>
          <Route path="/*" element={<App />} />
        </Routes>
      </AuthProvider>
    </BrowserRouter>
  </React.StrictMode>
);

index.js (server):

require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');

const sequelize = require("./config/database");

const verifyJWT = require('./middleware/verifyJWT');
const cookieParser = require('cookie-parser');
const credentials = require('./middleware/credentials');
const corsOptions = require('./config/corsOptions');

const PORT = process.env.PORT || 5000;


//Applying middleware
app.use(credentials); //Handle options credentials check before CORS and fetch cookies credential requirement
app.use(cors(corsOptions)); //Cross origin resource sharing
app.use(express.json()); 
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'client', 'build')));

//public routes
app.use('/auth', require('./routes/authRoutes'))
app.use('/postInviteId', require('./routes/postInviteId'))
app.use('/invites/:Id', require('./routes/inviteById'))
app.use('/application', require('./routes/postApplication'))

app.use(verifyJWT); //Anything below this has to have a verified JWT

//private routes
app.use('/invites', require('./routes/invites'))
app.use('/email', require('./routes/emails'))
app.use('/application', require('./routes/applications'))


app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});

sequelize.sync().then(() => {
}).catch((err) => {
  console.log(err);
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Network tab when attempting to navigate to a different page (in production):

enter image description here

Network tab when attempting to navigate to a different page (in localhost environment):
enter image description here

I have unfortunately been stuck on this one for a while now and would appreciate any input.

Building an Agenda / Calendar / Availability view with Firestore

I’m stuck. Stuck because Firestore is not (yet) capable to handle my (to me) relatively simple query. I don’t want anything fancy. All I wish to get from the database are the meetings that have not ended yet. But, I would like the list to be limited to 5 items, and ordered by the starting date of the meeting, to display a small “Up next” style Agenda.

However, the following is not a valid query:

where("end", "<", now), orderBy("start", "asc"), limit(5)); 

So, how do I achieve this rather simple query for my Agenda?


And, while we’re here, maybe we can dig into the other queries, too:

:: Display the last meeting (Already Over)

where("end", "<", now), orderBy("end", "desc"), limit(1))

:: Display the current meeting (Now) – Started, but not Ended.

.... ?????

:: Display the meetings which have not yet started (Next)

where("start", ">", now), orderBy("start", "asc"), limit(5))

The only thing that I can think of right now for the “current”, is to grab the array of all the meetings that have ended. Grab the array of all the future meetings, and an array of all meetings. Substract the (previous) and (future) arrays from the (all) list, and I’ll have the one meeting that hasn’t ended, but has already started. Theres gotta be a more efficient way to do this. No?

How do I limit a function for each user? [closed]

How to limit a function for each user?
Let me explain:

function getDay() {
  return new Date().getDay() + 1;
}

// Imagine here, A system to run this function for each user

For example, this function.

My aim is to make it 10 limit for each user. That is each user can use this 10 times after that they will be asked to purchase premium.

I hope you understood. Can you help me with this?

javascript + firebase: How to access nested object using this code?

link to the firebase screenshot

My firebase structure which I cant change unfortunately has this additional level which is 0 for all items. I am trying to build a webpage where I am listing my database. If I remove (to test) the level which is 0 for all the code works. However, the JSON file I am stuck with has this 0 level.

I am not sure how to adjust my code so that it will retrieve the name not from the first item underneath domain but “item underneath domain /0/”

Anyone any clue how to help a n00b out?

`

function FetchAllData() {
    firebase.database().ref('domain').once('value',function(snapshot){
        snapshot.forEach( 
            function(GrandChildSnapshot){
                let name = ChildSnapshot.val().Name;
                let roll = ChildSnapshot.val().Profile;
                let sec = ChildSnapshot.val().Type;
                let gen = ChildSnapshot.val().URL;

                addItemsToList(name,roll,sec,gen);
            }
            )
    });
}

window.onload(FetchAllData());

`

I tried to add a path into the variable but it did not retrieve correctly

Vuejs Pinia store with namespace

Can pinia actions be divided into two namespaces, such that access happens over property n1 and n2 such that:

// current
store.n1a('hi')
store.n2b()
// wanted
store.n1.a('hi')
store.n2.b()

// ugly workaround:
store.namespace1().a('hi')
// store would look like
  actions: {
    namespace1() {
      return {
        a(msg) {
          console.log(msg);
        }, 
      };
     ....
    },
  },

JavaScript Time Tracker Tool

I’m trying to build a web-based task time-tracker.

The tracker will be a stopwatch with the following fields:

1-Team Name (Drop Down field)
2-Task Name (Drop Down field)
3-Task Count (Manual Entry)
4-Start Time (Triggered when turning on stopwatch)
5-Stop Time (Triggered when turning off stopwatch)
6-Time Elapsed (Difference between start/stop time)
7-Submit Button (Manual Click)

The functionality will work as follows:
-A user will log the task/processor name and then click start on the stopwatch.
-The start time will be recorded in the start time field
-The user will perform a task a number of times
-The user will click the stopwatch again when done with the work they set out to complete
-The end time field will be automatically recorded when the stopwatch is paused
-The time elapsed will be calculated between the start and stop time
-The user will enter in the number of tasks they completed in the task count field
-The user will click submit
-When the submit button is clicked, all data in the fields above will be sent to a spreadsheet/storage location.

The stopwatch is intended to be used by several users on multiple machines.

How can I have this link to a data storage location where a complete list of all submitted data can be found? I need to know if the spreadsheet linking is a capability that can be web based?

CSS transition not working when toggling the display

I have a table that consists of products. between each row of products there is another row that will contain another table which will be the user’s inventory for that particular product above it.

By default, this inventory row contains the class d-none to hide the row when it is not expanded. This is because if I set the height of this row to 0 you can still see the row.

When the user clicks to expand the inventory row for a product, I toggle the d-none class and set the div height to 200px. The below expands the div’s height to 200px instantly and transition that I have set in the CSS is not followed.

css

.inventory {height: 0px; max-height: 200px; overflow-y: auto; transition: height .3s linear;}
.inventory.expanded{height: 200px;}

html

<tr class="data-row">
    ...
    <td class="mb-0 p-1 text-end" style="height: 36px"><h6 class="text-sm mb-0"><em class="table-icon fas fa-chevron-down text-primary cursor-pointer" onclick="expand_card(this)" id="" aria-hidden="true"></em></h6></td>
</tr>
<tr class="mb-0 p-1 d-none" id="inventory-table-">
    <td class="bg-gray-100 py-0 px-2" id="" colspan="8" style="vertical-align: top;"><div class="inventory" style="" id="inventory-div-"></div></td>
</tr>

js

function expand_card(e) {
    let open = e.classList.contains("open")
    if (open) {
        document.getElementById('inventory-table-' + e.id).classList.toggle('d-none');
        document.getElementById('inventory-div-' + e.id).classList.toggle('expanded')
        cards_inventory_table_delete(e.id)
        e.classList.remove("open")
    } else {
        document.getElementById('inventory-table-' + e.id).classList.toggle('d-none');
        document.getElementById('inventory-div-' + e.id).classList.toggle('expanded')
        cards_read(e.id)
        e.classList.add("open")
    }
}

If I removed the d-none class and remove the JavaScript to toggle this class, the transition for the div’s height works as expect but leaves a visible row even when the height is set to zero.

html

<tr class="data-row">
    ...
    <td class="mb-0 p-1 text-end" style="height: 36px"><h6 class="text-sm mb-0"><em class="table-icon fas fa-chevron-down text-primary cursor-pointer" onclick="expand_card(this)" id="" aria-hidden="true"></em></h6></td>
</tr>
<tr class="mb-0 p-1" id="inventory-table-">
    <td class="bg-gray-100 py-0 px-2" id="" colspan="8" style="vertical-align: top;"><div class="inventory" style="" id="inventory-div-"></div></td>
</tr>

js

function expand_card(e) {
    let open = e.classList.contains("open")
    if (open) {
        document.getElementById('inventory-div-' + e.id).classList.toggle('expanded')
        cards_inventory_table_delete(e.id)
        e.classList.remove("open")
    } else {
        document.getElementById('inventory-div-' + e.id).classList.toggle('expanded')
        cards_read(e.id)
        e.classList.add("open")
    }
}

Why is toggling the display causing the transition not to work?