Conditionally add to array of objects using spread operator

I would like to conditionally add something to an array using a spread operator if it matches a particular condition (ie. if the movie id does not match other movie id’s that already exist in my array)

case ADD_FAVORITE:
    return {
            ...state,
            favorites: [ state.favorites !== action.payload.id? ...state.favorites, action.payload]
    }

This is what I have tried

action payload returns something like this

{id: 0, title: 'The Godfather', director: 'Francis Ford Coppola', metascore: 100, genre: 'Drama', …}

and inside state.favorites:

description: "Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a Wookiee and two droids to save the galaxy from the Empire's world-destroying battle station, while also attempting to rescue Princess Leia from the mysterious Darth Vader."
director: "George Lucas"
genre: "Scifi"
id: 1
metascore: 92
title: "Star Wars"
[[Prototype]]: Object

Unable to target and remove appended element in jquery or Javascript

Here’s what I’m trying to do here –

  1. Take input from a form field and append the data in a div option-badges
  2. The badges have X button that I’m using to remove the items clicked if needed

What’s the problem?
With the code I’ve written, I’m unable to remove the said appended badge while I’m easily able to remove the badges which were there already.

Here’s the code. Please help me with this. Thanking in anticipation.

$(document).ready(function() {
  //take input data from first input field and display comma separated in second field
  let dataList = [];
  let dataString = "";
  $("#addData").on('click', function() {
    let data = $("#firstInput").val();
    let dataBadge = '<span class="badge badge-secondary" style="margin-left: 5px;">' +
      data + ' &nbsp <i id="newBadge" class="fa-solid fa-xmark" ></i></span>';
    $('.option-badges').append(dataBadge);
    $("#firstInput").val('');
  })

  //remove badge on clicking x
  $(".option-badges > span > i").on("click", function() {
    $(this).parent().remove();
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.1/css/bootstrap.min.css"  />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"  />
<div class="option-badges">
  <span class="badge badge-secondary" style="margin-left: 5px;">data  <i class="fa-solid fa-xmark"></i></span>
  <span class="badge badge-secondary" style="margin-left: 5px;">data  <i class="fa-solid fa-xmark"></i></span>
</div>

–

Data not working in global scope but in local scope

I have been trying to make an e-commerce website and in that almost all things are done except for the database part. In which I have to fetch the data from firebase and use it in the products section.
I have fetched the data in local variables, however I want to store the data in a global scoped object, but it is not working.
So what I basically want is I want to fetch the data from firebase(DONE) and store it in global scope object(PENDING) so that I can use this object in other .js files.
Any kind of idea/advice/help/suggestion in more than welcomed!!
Thanks in advance!

This is my code:
https://jsfiddle.net/kumartanwar123/gseh4coq/

OR

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-analytics.js";
// GLOBAL VARIABLES
var name, images, prices;
const firebaseConfig = {
  apiKey: "--",
  authDomain: "--",
  databaseURL: "--",
  projectId: "round-device-336118",
  storageBucket: "round-device-336118.appspot.com",
  messagingSenderId: "--",
  appId: "--",
  measurementId: "--",
};
const app = initializeApp(firebaseConfig);
firebase.initializeApp(firebaseConfig);
class firebase_class {
  constructor(Images, Prices, Name) {
    this.Images = Images;
    this.Prices = Prices;
    this.Name = Name;
  }
}
// FIREBASE DATA FETCH
firebase
  .database()
  .ref("Practice")
  .on("value", function (all_data) {
    all_data.forEach(function (current_data) {
      name = Object.keys(current_data.val().Name).map(
        (keys) => current_data.val().Name[keys]
      );
      //In this if I use console.log(name) then it is working just fine, but not in outside the function.
      images = Object.keys(current_data.val().Images).map(
        (keys) => current_data.val().Images[keys]
      );
      prices = Object.keys(current_data.val().Prices).map(
        (keys) => current_data.val().Prices[keys]
      );
    });
  });
let firebase_object = new firebase_class(images, prices, name);

How to latest data in array of objects database mongodb

I am trying to sort data in an array of objects. The problem is I don’t have any date property so I can’t be able to show the latest data,

I am trying to sort it like out this way but it is not working.

 const filter2 = data.sort((a, b) => (a > b ? -1 : 1))

Here is my data example

const data = [
        {
            _id: "6221943a03931299eb8c343b",
            title: "product 1",
            brand: "Beats",
            reg_price: "299",
            sale_price: "200",
            stock: "150",
        },
        {
            _id: "6221943a03931299eb8c343b",
            title: "product 2",
            brand: "Beats",
            reg_price: "299",
            sale_price: "200",
            stock: "150",
        },
        {
            _id: "6221943a03931299eb8c343b",
            title: "product 3",
            brand: "Beats",
            reg_price: "299",
            sale_price: "200",
            stock: "150",
        },
        {
            _id: "6221943a03931299eb8c343b",
            title: "product 4",
            brand: "Beats",
            reg_price: "299",
            sale_price: "200",
            stock: "150",
        },
        {
            _id: "6221943a03931299eb8c343b",
            title: "product 4",
            brand: "Beats",
            reg_price: "299",
            sale_price: "200",
            stock: "150",
        },
    ]

React axios await dispatch in UseEffect

I need to wait for my axios action to dispatch before continuing in UseEffect

import { getBrief } from '../../store/actions/agency-brief'
import agencyBriefReducer from '../../store/reducers/agency-brief-reducer'

    const [agencyBrief, dispatch] = useReducer(agencyBriefReducer, [])
    
          useEffect(async () => {   
            await getBrief(briefId)(dispatch);
            console.log('BRIEF', agencyBrief)
          }, [])

So console log here is undefined, I need to wait before

action:

export const getBrief = (briefID) => async (dispatch) => {
    try {
        let res = await axiosInstance.get(`/agency_briefs/reactGetBrief/${briefID}`)
        console.log('sre', res )
        return dispatch({ 
            type: 'GET_BRIEF', 
            payload: res.data
        }) 
     }
     catch (err) {
         console.error(err);
     }
}

reducer:

const agencyBriefReducer = (state, {payload, type}) => {
    switch (type) {
        case 'GET_BRIEF':
                return {
                    ...state,
                    brief: payload
                }   
        default:
            return state
    }
}

I’ve tried async / await but it doesn’t work, I need to wait so I can use the result to set the state ? Thanks

Using elements for multiple funcitons

As a beginner for javascript, I’m having some difficulties to build functions so that multiple functions use the same element on a page. The purpose of the function is to calculate and display a value based on the input of a user.

The function looks like this:

<script language='javascript' type='text/javascript'>

document.getElementById("n182849949").onblur= function() {
    reSumText1();
}
document.getElementById("n182849950").onblur= function() {
     reSumText1();
}
document.getElementById("n182849951").onblur= function() {
     reSumText1();
}
document.getElementById("n182849952").onblur= function() {
    reSumText1();
}

function Tonumber(numX) {
          return Number(numX.replace(".","").replace(" ","").replace(",","."))

}

function reSumText1() {
            var num1 = Tonumber(document.getElementById("n182849949").value);
            var num2 = Tonumber(document.getElementById("n182849950").value);
            var num3 = Tonumber(document.getElementById("n182849951").value);
            var num4 = Tonumber(document.getElementById("n182849952").value);
var sum2 = num1 + num2 + num3 + num4;
var sum3 = sum2.toLocaleString('de-DE');
            document.getElementById("1").innerHTML =sum3;

        }
 </script>

The function works fine, but as soon as two functions use the same element (e. g. “n182849952”) only the last one mentioned will work. How can this be solved?

Thanks a lot in advance!

How to get a date from a form in php?

sorry for my bad english…

I want to get a date from a a html form but I don’t success…

I have a form with an input *date *and an input *submit* :

<input type="date" placeholder="Enter date here" name="date">
<input type="submit" name="submit" value="Submit">

And I would like to get the date. So I tried this:

<form method="post">
              <input type="date" placeholder="Enter date here: 0000-00-00" name="date">
              <input type="submit" name="submit" value="Submit">
              
                <?php
                if (isset($_POST['date']))
                {
                    ?><script>alert(<?php echo $_POST['date']; ?>)</script> <?php
                }
                ?>
</form>

But when I click on submit, it displays a random date; example when I pick 2022-03-23, it displays 1996…

Someone can help me? I searched but I didn’t find a correct answer.

Thank You

What is exactly the event object?

I am starting to learn about event object this week, and I can not wrap my head around it.
Please, excuse any typo as english is not my native language, and I will try to be clear.

What is exactly event object? when is it executed? why do we have it?
For example:

  1. when we use an anonymous function as in this example, the event object will not be renderPosts() function.

window.addEventListener(‘DOMContentLoaded’, () => renderPosts());

const renderPosts = async () => {
  let uri = 'http://localhost:3000/posts?_sort=likes&_order=desc';
  const res = await fetch(uri);
  const container = document.querySelector(".blogs");
  1. when we do not use anonymous function as in this example, the event object will be renderPosts() function.

window.addEventListener(‘DOMContentLoaded’,renderPosts());

const renderPosts = async () => {
  let uri = 'http://localhost:3000/posts?_sort=likes&_order=desc';
  const res = await fetch(uri);
  const container = document.querySelector(".blogs");

I do not see the difference and not really understand it. I have been searching about event object, but still confused.

Appreciate any explanation.

Handle multiple checkbox components in React

I´m having issues with creating my checkbox component(s).
Since I´m mapping over an object´s entries, where the keys are the sectiontitles and the values are arrays, filled with the checkable features.

I´m also using tailwind. I will let the code speek for itself I think 😀

Checkboxes

Object structure, which im passing as a prop, down to the checkboxes component:

const features = {
  Features: [
    'Mintable',
    'Burnable',
    'Pausable',
    'Permit',
    'Votes',
    'Flash Minting',
    'Snapchots'
  ],
  'Access Control': ['Ownable', 'Roles'],
  Upgradeability: ['Transparent', 'UUPS']
}; 

Checkboxes component, which renders the checkbox component multiple times by mapping over the object (Ik the id is missing, but I dont know how to control the ID´s:

import React from 'react';
import { connect, useDispatch } from 'react-redux';

import Checkbox from '../../layout-blueprints/Checkbox';

import { featureCheckboxClick } from './Redux/actions';

const FeaturesComponent = ({ features }) => {
  const dispatch = useDispatch();

  return (
    /* Card layout and heading */

    <div className="bg-white p-4 rounded col-span-2 row-span-5">
      {Object.entries(features).map(([key, value]) => {
        return (
          <div key={key}>
            <h5 className="text-black m-t-4">{key}</h5>
            <div className="border-bottom border-primary pb-2 mb-4 mr-20">
              {/* Render feature checkboxes */}

              {value.map((feature) => {
                return (
                  <div className="flex justify-between m-2" key={feature}>
                    <div>
                      <Checkbox
                        onChange={() => dispatch(featureCheckboxClick(feature))}
                      />
                      <span className="pl-2 text-lg">{feature}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default connect()(FeaturesComponent);

checkbox-component:

import React from 'react';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCheck } from '@fortawesome/free-solid-svg-icons';

const Checkbox = () => {
  return (
    <label htmlFor="check-box-1" className="cursor-pointer relative">
      <input
        type="checkbox"
        className="check-box-1 appearance-none h-4.5 w-4.5 border-2 border-primary rounded-sm relative translate-y-0.5"
      />
      <FontAwesomeIcon
        icon={faCheck}
        className="-translate-x-4 translate-y-0.5 h-4.5 w-4.5 text-sm absolute text-white text-opacity-0 transition check-1 duration-200"
      />
    </label>
  );
};

export default Checkbox;

css tailwind directives (should be readable, even if you never worked with tailwind):

@tailwind components;
@tailwind utilities;

.check-box-1:checked {
  @apply bg-primary;
}

.check-box-1:checked ~ .check-1 {
  @apply text-opacity-100;
}

That´s all the code. Like I said, I´d usually work with a useState array or so, but It´s kinda hard to control it, bc there is so much nesting in the mapping, or am I thinking too complicated?

I´m honestly clueless and am glad for any help I can get, cheers!

Blinking text cursor without focus in the HTML-text input

I have a HTML-text field with some input. The focus of the input is lost since I searched in another component. From the search results I need to insert some text where the cursor/caret is located.

Since the focus is lost the cursor won’t blink anymore. But than it gets hard to know the insert position for the user. Is there a chance to have a blinking caret/cursor without having the focus?

The solution has the problem that it won’t blink on the position the caret is currently located. If there is another UX-pattern for letting the user know where the text will be inserted I would welcome this idea as well.

Remark: The framework I’m coding with is Angular. Therefore JS, Typescript or Angular code is possible.

Implicit VSCode Intellisense no longer work after renaming the JS file

Earlier, I have two JS files:

  1. old-file.js
  2. new-file.js

I later noticed that my app.js‘ intellisense was always referring to the old-file.js but not the new-file.js, so I deleted the old-file.js (as though I’ve renamed the old file). But now, when working on my app.js, the intellisense has gone missing, which means VSCode does not automatically make use of the definitions in the new-file.js, which has the same and also additional object declarations.

I tried looking for my Typescript and JavaScript Language Features built-in extension but can’t find it in my VSCode. I also restarted my VSCode many times but still not working. My jsconfig.json looks fine in the project root folder as shown below:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "jsx": "preserve"
    },
    "exclude": [
        "node_modules",
        "**/node_modules/*"
    ],
    "typeAcquisition": {
        "include": [
            "jquery",
            "angular"
        ]
    }
}

Note that I was talking about the “implicit intellisense” of VSCode across external files, no import statements, nothing. Also note that my app.js and new-file.js will always be merged as app.min.js by terser at the later stage. Does anyone know what happen to my situation and how can I restore the intellisense of my new-file.js and put it back to work like the old one? Many thanks!

How to JSON.parse directly in html file in Typescript / Angular, or access json fields as objects?

after not finding an answer for what I was looking for, i’m asking this question.

Due to the fact that I need to avoid duplicates in a map, I had to stringify the map key. But later in the HTML file i need to get key’s fields in order to display and style.

Is there a way to achieve my goal?

component.ts:

criteriaFilters = new Map<any, boolean>();

ngOnChanges() {
    if (this.audit.getValue().chapitres) {
      for (const chapitre of this.audit.getValue().chapitres) {
        for (const auditCritereEval of Object.entries(chapitre.auditCritereEvaluations)) {
          if (auditCritereEval !== undefined) {
            if (auditCritereEval != null) {
              if (!this.criteriaFilters.has(JSON.stringify(auditCritereEval))) {
                console.log(auditCritereEval);
                this.criteriaFilters.set(JSON.stringify(auditCritereEval), true);
              }
            }
          }
        }
      }
      this.criteriaFilters.set('NOTSEEN', true);
    }
  }

component.html:

<div class="row mb-3">
        <div class="col-12">
          <label>{{'audit.filter.critere'}}</label>
          <div>
            <mat-button-toggle-group multiple (change)="updateCriteriaFilter($event)">
              <ng-container *ngFor="let filter of criteriaFilters.keys()">
                <mat-button-toggle *ngIf="filter != 'NOTSEEN'"  [value]="filter" [checked]="true">
                  <i class="las la-square-full" [style.color]="JSON.Parse(filter).value.color"> </i>
                  {{JSON.Parse(filter).value.label}}
                </mat-button-toggle>
                <mat-button-toggle *ngIf="filter == 'NOTSEEN'" [value]="filter" [checked]="true">
                  <i class="las la-eye-slash"></i>
                  {{ 'EE.Core.Audit.Audit.Results.Unseen' | translate }}
                </mat-button-toggle>
              </ng-container>
            </mat-button-toggle-group>
          </div>
        </div>
      </div>

JSON representation of the key [which is also a map(chapitre.auditCritereEvaluations)]:

[
    "23102",
    {
        "id": 23102,
        "label": "Conforme",
        "shortLabel": null,
        "reportingLabel": "Conforme",
        "position": 0,
        "color": "#008000",
        "conforme": true,
        "nonApplicable": false,
        "note": 1,
        "auditTypeCritereEvaluationId": 8331
    }
]

So as you see I need to access fields in the <i> tag (especially the label and color fields) when the filter is not ‘NOTSEEN’ (inside the first *ngif). So I wanna know if there’s anything to put in place of the JSON.parse() in the html file in order to access fields. If possible I would like not to have to create a TS function.

Thanks In advance for your answers.

Dearest StackOverflow community, my code is not working. Error. Please fix

Dearest StackOverflow community and my sincerest apologies for your losses.
This code I wrote does not work. I am very sorry to ask, but I need your help. I feel emberassed. I shouldn’t need to ask a question. I understand that you might be overwhelmed now, and that its hard to accept your fate. This question will be the only question I will ask, and I am very sorry to ask. I really feel emberassed. You need to believe me. This time, I will mention my code as expected from me. The code is written in JavaScript, a scripting language commonly used in Browsers. This code is supposed to do something very special. Thanks for reading this and attempting to fix my issue.

export const getCanvasMousePos = (canvas, evt) => {
    var rect = canvas.getBoundingClientRect();
    var scaleX = canvas.width / rect.width;
    var scaleY = canvas.height / rect.height;
    var ratioHW = canvas.height / canvas.width;
    var ratioWH = canvas.height / canvas.width;

    var rot = getCurrentRotation(canvas);

    var pos = {
        x: evt.offsetX,
        y: evt.offsetY
    }

    if(rot == 90) {
        pos = {
            x: pos.x * scaleX * ratioHW,
            y: (canvas.width - ((rect.width - (pos.y)) * scaleX)) * ratioWH
        };
    }else {
        pos = {
            x: pos.x * scaleX,
            y: pos.y * scaleY
        }
    }

    console.log(pos, ratioHW, ratioWH);
    //canvas.getContext("2d").fillRect(pos.x, pos.y, 5, 5);

    return pos;

    throw "sbeve";
}

JS error troubleshooting: TypeError Failed to fetch [closed]

I have one react application (ts+nextjs) deployed in production.
I am using sentry to capture all unhandled exceptions.

I have one issue:
I get a lot of TypeError Failed to fetch issues during the day for different assumed api calls.

I check the data across my backend and see that backend returned 200 status code correctly, but sentry/js thinks that it failed to fetch. I cannot reproduce this myself neither does any customer complain (at least not yet)
Just one of many examples in Sentry:

enter image description here

For the screenshoot above for example I verified that the api call to /api/ql endpoint at particular time for particular requestid went through fine and returned 200 status code, but I still don’t understand why here it fails.

Normally failed to fetch is thrown by

  1. cors issues
  2. wrong header sent get istead of post and so on
  3. etc that i don’t know

In this case request seem to be gone through fine to backend with GET method as from backend logs.

Please any ideas how to troubleshoot further this issue and also solve it?
Thank you