How can I alert the success message after I deleted all zero quantity on Angular CLI?

When I click the delete button it will delete all the products with zero quantity. I add an alert message to notify the user if the table has zero quantity or not. The success message will alert after deleting all the products with zero quantity and the error message alert if the table has no zero quantity. I’m using the sweetalert2. The problem is when I deleted all products that have zero quantity the error message showed instead of the success message. I want to show the success message after I deleted products and the error message only shows if the table has no zero quantity. How can I alert the success after I deleted all the products with zero quantity?

//Delete all row with zero quantity

public onDeleteProduct(): void {
    this.productServive.deleteProduct().subscribe(
      (response: void) => {
        console.log(response);
        this.messageShow();
        this.getAllProduct();
        this.onCloseUpdateHandled();
      },
      (error: HttpErrorResponse) => {
        this.errorMessage(error.message);
      }
    );
  }

// search if the product quantity is zero or not

public messageShow(): void {
    for(const product of this.products) {
      if(product.quantity === 0) {
        this.successMessage("deleted");
      } else {
        this.errorMessage("No more out-of-stock");
      }
    }
  }

//html

<button type="button" class="btn btn-outline-danger btn-sm" (click)="onDeleteProduct()">Delete</button>

//example table
enter image description here

How to call a JavaScript user extension function from Saxon-JS?

In Java based Saxon (like 8.1.1 that I am still running after more than a decade) it was super easy to call on your own Java extension functions from within XPath, and moderately easy to build your own extension elements. The documentation had an “Extensibility” section just before “Saxon Extensions”. Now in Saxon-JS, I see the “Extensibility” discussion conspicuously absent. Does this mean there is no way to easily call on your own javascript functions from within XPath run by Saxon-JS?

I already imagine a way to work around that … but I’m weary to say it in fear of Michael Kay shutting that loophole down? I’m going to do it anyway: I think we could use his ixsl extension to drop script elements into a scratchpad area, where they would be executed and leave their result which then would be fetched back. But this seems a rather expensive round-about way of doing it.

Nothing simpler?

Path.split is not a function in react Hook Form?

I am using React-Hook-Forms and I have a custom component for my input:

   export default function Input({
  name,
  label,
  value,
  placeholder,
  register,
  ...props
}: IProps) {
  const { control } = useForm();

  return (
    <div className="inputDefaultContainer ">
      <label htmlFor={name}>{label}</label>
      <input
        type="text"
        ref={register}
        name={name}
        className="poppins my-2"
        placeholder={placeholder}
        value={value}
        {...props}
      />
    </div>
  );
} 

I am using this in my form (which have more fields, that are similar to the ):

<form onSubmit={handleSubmit(postData)}>
          <div className="input-box">
            <Input
              name="precoProduto"
              label="Preço:"
              register={register}
              placeholder="R$ 00,00"
            />   
          </div>
        <div className="save">
          <SaveBtn />
        </div>
      </form>

The when I try to use the “Register” is getting the following error. Can you help me to resolve this?

get.ts:11 Uncaught TypeError: path.split is not a function
at get (get.ts:11:1)
at register (createFormControl.ts:924:1)
at commitAttachRef (react-dom.development.js:20875:1)
at commitLayoutEffects (react-dom.development.js:23431:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at commitRootImpl (react-dom.development.js:23151:1)
at unstable_runWithPriority (scheduler.development.js:468:1)
at runWithPriority$1 (react-dom.development.js:11276:1)

Way to use fastest-validator npm with typescript EXAMPLE

Code example of fastest-validator : javascript

const Validator = require("fastest-validator"); // javascript require

const v = new Validator();

const schema = {
    id: { type: "number", positive: true, integer: true },
};

const check = v.compile(schema);
// It work!

But if typescript usually i use this…

import Validator from "fastest-validator";
console.log(Validator) // undefined
const v = new Validator() // error because "Validator" is undefined not class

typescript import can read “index.d.ts” file. Validator is Class Validator (default export).
But return variable is “undefined“. You can “console.log(Validator)” for check.

Way to fastest-validator work with typescript with full declared in “index.d.ts” file.

Example Code

import type ValidatorType from "fastest-validator"; // You can rename "validatorType" to whatever do you need.
const Validator = require("fastest-validator"); // javascript require. Type is any.

const v: ValidatorType = new Validator();

Now It will work with full class declared.

Example Code

import type ValidatorType from "fastest-validator"
import type {
  AsyncCheckFunction,
  RuleEmail,
  RuleString,
  SyncCheckFunction,
  ValidationSchema,
} from "fastest-validator"

export const schema: ValidationSchema<{ // You can add some interface or type or skip this if you want.
  email: RuleEmail
  password: RuleString
}> = {
  email: {
    type: "email",
    max: 320,
  },
  password: {
    type: "string",
    pattern:
      // /^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,64}$/,
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[~`!@#$%^&*()-=[];'\,./_+{}|:"<>?]*)[A-Za-zd~`!@#$%^&*()-=[];'\,./_+{}|:"<>?]{8,64}$/,
  },
}

// CheckEmail has been declared type from compile function return.
const CheckEmail = v.compile<{ // also you can add some interface or type or leave it empty.
  email: typeof schemaValidation.email
}>({ ...schemaValidation.email, $$root: true })

const email = "[email protected]"

console.log(CheckEmail(email))

Credit regex password from some Stack Overflow

Firebase fetching + React: Images won’t load and getting a 500 error, but if I keep refreshing they show up

So I’m currently brushing up my react skills and learning firebase. I found it simple enough to configure and now I have been successfully making fetch requests from my realtime database.

I am currently building some sort of a birthday app that would show monthly and daily celebrants, and have generated mock data that I imported into my database. Currently, the first names are being fetched successfully and displaying on the screen, however the images (that are hosted on another site and fetched as a string from the db) are not loading properly and I’m getting 500 error in my console. If I keep refreshing though, they eventually load.

I’m thinking it must be with the way I make my fetch request. I basically fetch all users and then make a filter (have not explored fetching with queries yet) so I thought it would work.

This is the code for the fetch requests.

export const getUsers = () => {
    const usersDb = ref(database);
    return get(child(usersDb, `/users`)).then((snapshot) => {
        return snapshot.val();
    });
};


export const getMonthlyCelebrants = async () => {
    const users = await getUsers();
    const monthlyCelebs = [];
    for (let user in users) {
        const userMonth = +users[user]["birth_date"].split("/")[1];
        userMonth === getMonthNum() && monthlyCelebs.push(users[user]);
    }
    return monthlyCelebs;
};

And this is the Monthly Celebrants component I use them in:

export default function Monthly() {
  const [monthlyCelebs, setMonthlyCelebs] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function loadPage() {
      setIsLoading(true);
      const users = await getMonthlyCelebrants();
      setIsLoading(false);
      setMonthlyCelebs(users);
    }
    loadPage();
  }, []);

  return (
    <div>
      <h2>{getMonthAndYear()} Celebrants</h2>
      {isLoading ? (
        <p>Celebrants loading...</p>
      ) : (
        sortBirthdays(monthlyCelebs).map((monthlyCeleb) => {
          return (
            <SingleMonthlyCelebrant
              monthlyCeleb={monthlyCeleb}
              key={`${monthlyCeleb.birth_date}${monthlyCeleb.first_name}`}
            />
          );
        })
      )}
    </div>
  );
}

Any tips or advice would be greatly appreciated. Thank you!

How to get Selected Checkbox value by ID

Currently my code it works well with the input name, I can get the input value by input name
But I want my script to retrieve the input value with id input and not with name input?

here my code :

  $(document).ready(function () {
            $('input[type="checkbox"]').click(function () {
                getSelectedCheckBoxwithValueText("test")               
            });
            var getSelectedCheckBoxwithValueText = function (name1) {
                var data = $('input[name="' + name1 + '"]:checked');
                if (data.length > 0) {
                    var resultdata='' ;
                    data.each(function () {
                        var selectedValue = $(this).val();
                         resultdata += $('label[for="cb-' + selectedValue + '"]').text() + "<br/>";
 
                    });
                    $("#divchecked").html(resultdata);
                }
                else {
                    $("#divchecked").html("No Check box selected");
                }
                
 
            };
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
    checked:
    <input type="checkbox" id="c1" name="test" value="cricket" />
    <label for="cb-cricket">Cricket</label>
    <input type="checkbox" id="c2" name="test" value="swimming" />
    <label for="cb-swimming">Swimming</label>
    <input type="checkbox" id="c3" name="test" value="blog" />
    <label for="cb-blog">Blog</label>
    <input type="checkbox" id="c4" name="test" value="coding" />
    <label for="cb-coding">Coding</label>
    <br/>
    <br/>
    Selected checkbox:<br />
    <div id="divchecked"></div>
</body>

jsfiddle code : enter link description here

Javascript Lodash replace array with another

I’m trying to manipulate an array like this:

data = [
   {
      "id":"1",
      "items":[
         {
            "title":"item 1"
         },
         {
            "title":"item 2"
         }
      ]
   },
   {
      "id":"2",
      "items":[
         {
            "title":"item2 1"
         },
         {
            "title":"item2 2"
         }
      ]
   }
]

I need, for example, to push another array:

      [
         {
            "title":"item new 1"
         },
         {
            "title":"item new 2"
         }
      ]

inside data[0].items and obtain:

data = [
       {
          "id":"1",
          "items":[
             {
            "title":"item new 1"
         },
         {
            "title":"item new 2"
         }
          ]
       },
       {
          "id":"2",
          "items":[
             {
                "title":"item2 1"
             },
             {
                "title":"item2 2"
             }
          ]
       }
    ]

…how can I do this maintaining immutability, for example with Lodash?
Not understand anding how to change only a specific sub object in a data structure.
Somebody have suggestions?

Thanks

Uncaught TypeError: Cannot read properties of undefined (reading ‘url’)

I’m new to react js, I’m getting Uncaught TypeError: Cannot read properties of undefined (reading ‘url’) error due to fetching images map. If I use data already on the file, it works fine, but if I have to fetch the data, it creates This error. This is what is tried. please let me know how to fix this error.

 const THECATAPI = 'https://api.thecatapi.com/v1/breeds'

  const [catList, setCatList] = useState([])


       const axiosPosts = async () => {
      try {
        const response = await axios(THECATAPI)
        setCatList(response.data)
      } catch (error) {
        console.log('erroRRRR');

      }
    };



 
   // return 
<div>

 
    {
        catList.map((obj, i) => (
            <div >
                <img src={obj['image']['url']} alt='loading' />
            </div>
    }

</div>

Javascript beginner programming quesion

This is my coding.

switch(education){
case “no highschool diploma”:
salary=”25636″;
break;
case “a high school diploma”:
salary=”35256″;
break;
case “an Associate’s degree”:
salary = “41496”;
break;
case “an Bachelor’s degree”:
salary = “59124”;
break;
case “an Master’s degree”:
salary = “69732”;
break;
case “an Professional degree”:
salary = “89960”;
break;
case “an Doctoral degree”:
salary = “84396”;
break;
}
console.log(“In 2015, a person with “+education+” earned an average of “+ salary.toLocaleString(“en-US”) +”/year.”);

I wanna know why the result is
In 2015, a person with a high school diploma earned an average of 35256/year.
Instead of
In 2015, a person with a high school diploma earned an average of 35,256/year.

Where am I wrong?

vite – adding custom build steps for a file

I have a vuejs app that has a default entry point in index.html/main.js

Now I would like to include an additional file sw.js (service worker), which is a standalone file, that is not referenced in main.js.

As preliminary step – this file requires the workbox-build command to be executed after vite has already created main js bundles and other files in /dist folder. workbox-build will generate a file in dist/sw.js. Afterwards the file needs to resolve imports and be minified.

I am currently relying on a following hacky solution:

vite build && node ./postbuild.js

where the ./postbuild.js job is:

npx workbox-cli injectManifest workbox-config.js -> replaces variables inside the file
npx vite build --config vite.ws.config.js -> imports resolution + minification

I would like to join these steps. (for convenience and possibly better performance)

Do I need to write a rollup/vite plugin, or is it possible to be done just by adding some configuration into existing/main vite config?

Don’t know where to start..

postcss config error within vue app cannot import css into component

I have a vue component that is pulling css from node_modules and also from it’s own relative file structure like below,

import "splitpanes/dist/splitpanes.css";
import "../../sass/splitpanes.css";

When trying to build our vue app we get the following error,

Syntax Error: Error: No PostCSS Config found in: /codebuild/output/src971107930/src/webapps/node_modules/splitpanes/dist
@ /codebuild/output/src971107930/src/webapps/node_modules/splitpanes/dist/splitpanes.css 4:14-142
@ /codebuild/output/src971107930/src/webapps/node_modules/cache-loader/dist/cjs.js??ref--13-0!/codebuild/output/src971107930/src/webapps/node_modules/babel-loader/lib!/codebuild/output/src971107930/src/iwebapps/node_modules/cache-loader/dist/cjs.js??ref--1-0!/codebuild/output/src971107930/src/webapps/node_modules/vue-loader/lib??vue-loader-options!../components/src/components/workspaces/Dashboard.vue?vue&type=script&lang=js&
@ ../components/src/components/workspaces/Dashboard.vue?vue&type=script&lang=js&
@ ../components/src/components/workspaces/Dashboard.vue
@ ../components/src/components/index.js
@ /codebuild/output/src971107930/src/webapps/node_modules/cache-loader/dist/cjs.js??ref--13-0!/codebuild/output/src971107930/src/webapps/node_modules/babel-loader/lib!/codebuild/output/src971107930/src/webapps/node_modules/cache-loader/dist/cjs.js??ref--1-0!/codebuild/output/src971107930/src/webapps/node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=script&lang=js&
@ ./src/App.vue?vue&type=script&lang=js&
@ ./src/App.vue
@ ./src/main.js
@ multi ./src/main.js

In the root of the project we do have a postcss.config.js file,

module.exports = {
  plugins: {
    'postcss-advanced-variables': {},
    tailwindcss: {},
    'postcss-import': {},
    'postcss-nested': {},
    'postcss-color-function': {},
    autoprefixer: {},
  }
}

Is it complaining about this one, or complaining about the fact that the node module does not have one pictured is the file structure of the package from node_modules,

enter image description here

Is there a fix or workaround for this problem, am I doing something wrong?

Adding/removing classes to/from element scrolls page to the top?

I have to following code:

const burger = $("#burger-menu");
const main = $("#main");
const menu = $("#menu");

function showSideMenu() {
  $("#menu").removeClass("hidden");
  $("#main").addClass("blurry");
  $("#main").addClass("fixed");
  burger[0].childNodes[1].childNodes[1].classList.add("burger-top-animate");
  burger[0].childNodes[1].childNodes[3].classList.add("burger-bottom-animate");
}

function hideSideMenu(event) {
  $("#menu").addClass("hidden");
  $("#main").removeClass("blurry");
  $("#main").removeClass("fixed");
  burger[0].childNodes[1].childNodes[1].classList.remove("burger-top-animate");
  burger[0].childNodes[1].childNodes[3].classList.remove(
    "burger-bottom-animate"
  );
}

burger.click((event) => {
  event.preventDefault();
  if (menu.hasClass("hidden")) showSideMenu();
  else hideSideMenu();
});


the burger click event handles a collapsing sidebar menu(hiding/showing). It behaves as expected, except it scrolls the page to the top. I can’t explain to myself how that might be happening and I couldn’t find the problem anywhere else.

The prevent default does not change as a thing.

Any help is appreciated!

can’t get a picture from different links

I have express server and special folder for images.

app.use(express.static("files"));

And if I try to get an image, for example, in localhost:3000/test from the files folder, it works. But if I try to get an image for example in localhost:3000/profile/404 from the same folder – it doesn’t work