How to prevent filtered array from destroy in Angular?

I am trying to filter an array of users, but when I click on reset data is not coming back.
Please guide me on how can I fix this.

  filterUsers(event:any) {
    this.users = this.users.filter(user => {
      return user.displayName.toLowerCase().includes(event.target.value.toLowerCase());
    })
  }

Any solution appreciated!

fs.readFileSync doesn’t read file, neither throws error

This is my code.

socket.on('readNames', function () {
        console.log("Connected!");
        fs.readFileSync('client/message.txt', function (err, data) {
            if (err) throw err;
            console.log("1");
            var lines = data.split('n');
            var html = '<table>';
            console.log("2");
            for (var i = 0; i < lines.length; i++) {
                var line = lines[i].split(' ');
                html += '<tr>';
                console.log("3");
                for (var j = 0; j < line.length; j++) {
                    html += '<td>' + line[j] + '</td>';
                }
                console.log("4");
                html += '</tr>';
            }
            html += '</table>';
            for (var i in lines.length) {
                console.log("5");
            }
        });
    });

The “Connected!” message gets logged in the terminal, so I am entering the function, but the fs.readFileSync doesn’t work..? It doesn’t throw an error, neither return the 1 I’m asking it to log as soon as it enters. I also tried removing everything inside and just keeping the console.log(“1”) there, but still doesn’t work.
I’ve been stuck on this a little now so any help would be appreciated.

How to correctly add the src to printThis.js

Whenever I add the references in javascript it keeps saying that the references cannot be loaded. I have downloaded the packages and have them sitting in a file called Data/NGData/Dependencies/Packages.
I would have thought that the src would look like this

<script src="/Data/NGData/Dependencies/Packages/printThis.js"> </script>

But that doesn’t work. Can anyone give me some pointers so that I can use the library.

EDIT: The error that I’m getting The error that I'm getting

TypeError: n.indexOf is not a function while Deleting doument from Firebase/Firestore

I have a files collection in fireStore which has fileId as one of the documents field & I’m trying to delete document using the fileld(by where clause) but It throws an error –
See the error in the picture below –

enter image description here

The following lines of code lead to the above errors-

try {
                await deleteDoc(doc(db, "files", where('fileId', "==", deletee.fileId)));
                AddToast("success", "File deleted successfully", toastDispatch);
            } catch (error) {
                console.log(error);
                AddToast("error", "Couldn't delete try again!", toastDispatch);
            }

Note : deletee.fileId has a value, so that is not a problem at all.

how to manage read and unread notification in react?

I’m working in react js and I want to develop notifications component which related to the account related activities. I have to display all the account related activities in the notifications list and sort them as a read and unread notifications.

so the my question is how to manage read and unread notification in react/ next js ?

Do I need to make it state or session storage ?

consider this is my notification list :

const notificationArray = [
  { id: 1, msg: 'one' },
  { id: 2, msg: 'two' },
  { id: 3, msg: 'three' },
  { id: 4, msg: 'four' },
  { id: 5, msg: 'five' },
];

And in the below list I have received one new notification :

const notificationArray = [
  { id: 1, msg: 'one' },
  { id: 2, msg: 'two' },
  { id: 3, msg: 'three' },
  { id: 4, msg: 'four' },
  { id: 5, msg: 'five' },
  { id: 6, msg: 'six' }
];

AsyncData not being called in nuxt

I want to set category data at asyncData hook. But MainHeader Page Component never called asyncData even if it is placed on page components. Can you explain why MainHeader Page Component not calls asyncData?

MainHeader is placed inside “com” folder which is placed on pages (pages/com/MainHeader)

<template>
  <div>
    <header-nav :cateList="cateList"/>
  </div>
</template>

<script>
import HeaderNav from '~/components/com/nav/HeaderNav.vue';
import CateApi from "~/util/api/category/cate-api";

export default {
  components: {HeaderNav},

  async asyncData(){
    const cateList = await CateApi.getDispCateList();
    return{
      cateList,
    }
  },

  data() {
    return {
      cateList: [],
    }
  },
}
</script>

default
(layouts/default)

<template>
<div>
  <main-header/>
  <Nuxt/>
</div>
</template>

<script>
import MainHeader from "~/pages/com/MainHeader.vue"
export default {
  components :{
    MainHeader,
  },
  name: "defaultLayout"
}
</script>

Props not passing to component React

I’m trying to clean up my code and have moved a large chunk into it’s own component, although now nothing is rendering in the component I’ve moved, and the props aren’t passing through to my MovieComponent.

app.js:

import React, { useState } from "react";
import "./App.css";
import styled from "styled-components";
import movieicon1 from "./icons/movieicon1.png";
import MovieComponent from "./components/MovieComponent";
import api from "./api/Api";

const Container = styled.div`
  display: flex;
  flex-direction: column;
`;
const Header = styled.div`
  display: flex;
  flex-direction: row;
  background-color: black;
  justify-content: space-between;
  color: white;
  align-items: center;
  padding: 10px;
  font-size: 25px;
  font-weight: bold;
  box-shadow: 0 3px 6px 0 #555;
  justify-content: space-evenly;
`;
const AppName = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
`;
const MovieImage = styled.img`
  width: 48px;
  height: 48px;
  margin: 15px;
`;
const MovieListContainer = styled.div`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  padding: 30px;
  gap: 24px;
  justify-content: space-evenly;
`;
function App() {


  const [error, setError] = useState(false);

  return (
    <Container>
      <Header>
        <AppName>
          <MovieImage src={movieicon1} />
          Prince's Theatre
        </AppName>
      </Header>
      {error ? <div>Oops there seems to be a problem please refresh</div> : ""}

      <MovieListContainer>
        
          <MovieComponent />
       
      </MovieListContainer>
    </Container>
  );
}

export default App;

I’ve moved the majority of code into my MovieListContainer:

import React, { useState, useEffect, useMemo } from "react";
import MovieComponent from "./MovieComponent";
import api from "../api/Api";

function MovieListContainer() {
  const [error, setError] = useState(false);
  const [filmWorld, setFilmWorld] = useState([]);
  const [cinemaWorld, setCinemaWorld] = useState([]);
  useEffect(() => {
    const theaters = ["cinema", "film"];
    theaters.forEach((theater) => {
      async function getTheater() {
        const data = await api.getMoviesData(theater);
        if (data == null) {
          setError(true);
          return;
        }
        if (data.Provider === "Film World") {
          setFilmWorld(data);
        } else {
          setCinemaWorld(data);
        }
      }
      getTheater();
    });
  }, []);

  const movies = useMemo(() => {
    if (!filmWorld.Provider) return [];
    return filmWorld.Movies.map((movie, index) => ({
      ...movie,
      cinemaWorldPrice:
        cinemaWorld.Provider && cinemaWorld.Movies[index]?.Price,
    }));
  }, [filmWorld, cinemaWorld]);

  return movies.map((movie, index) => (
    <MovieComponent key={index} movie={movie} error={error} />
  ));
}

export default MovieListContainer;

and from here it seems that the props aren’t making it to my MovieComponent:

import React from "react";
import styled from "styled-components";
import PriceCheckIcon from "@mui/icons-material/PriceCheck";
import CurrencyFormat from "react-currency-format";

const MovieContainer = styled.div`
  display: flex;
  flex-direction: column;
  padding: 10px;
  width: 280px;
  box-shadow: 0 3px 10px 0 #aaa;
  cursor: pointer;
`;
const CoverImage = styled.img`
  height: 362px;
`;
const MovieName = styled.span`
  font-size: 18px;
  font-weight: 600;
  color: black;
  margin: 15px 0;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
`;
const InfoColumn = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-end;
`;
const MovieInfo = styled.span`
  font-size: 18x;
  font-weight: 500;
  color: black
  text-transform: capitalize;
  
`;

const MovieComponent = (props) => {
  const { Poster, Price, Title, cinemaWorldPrice } = props.movie;
  const { error } = props;
  return (
    <MovieContainer data-testid="movieComponent-1">
      <CoverImage src={Poster} alt="" />
      <MovieName>{Title}</MovieName>

      <InfoColumn>
        <MovieInfo>
          FilmWorld: &nbsp;
          <span
            style={
              Price < cinemaWorldPrice ? { color: "green" } : { color: "red" }
            }
          >
            <CurrencyFormat
              value={Price}
              displayType={"text"}
              prefix={"$"}
              decimalScale={2}
              fixedDecimalScale
            />
          </span>
        </MovieInfo>
        <MovieInfo>
          CinemaWorld: &nbsp;
          <span
            style={
              Price > cinemaWorldPrice ? { color: "green" } : { color: "red" }
            }
          >
            {error === "Server Error" && Price > cinemaWorldPrice ? (
              <PriceCheckIcon />
            ) : (
              <CurrencyFormat
                value={cinemaWorldPrice}
                displayType={"text"}
                prefix={"$"}
                decimalScale={2}
                fixedDecimalScale
              />
            )}
          </span>
        </MovieInfo>
      </InfoColumn>
    </MovieContainer>
  );
};

export default MovieComponent;

WordPress Uncaught ReferenceError: url is not defined ajax [closed]

I’m writing a module for WordPress, I’m trying to connect ajax, but it doesn’t work. I can’t find any information on how to deal with this. I know how to use ajax in a regular project, but I started using it in wp, nothing happens.

Uncaught ReferenceError: dip_url is not defined

PHP FILE

function dip_register_assets(){
    wp_register_script('dip_script', plugins_url('dip.js', __FILE__));
}
add_action( 'admin_enqueue_scripts', 'dip_register_assets');

function dip_load_assets($hook){
    if($hook != 'toplevel_page_dip-options'){
        return;
    }

    wp_enqueue_script('dip_script');
}
add_action('admin_enqueue_scripts', 'dip_load_assets');

//adasdasd
wp_localize_script( 'dip_script', 'dip_url', array(
    'ajax_url' => admin_url('admin-ajax.php')
) );

function example_localize_ajax(){
    wp_localize_script('jquery', 'ajax', array(
        'url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('example_ajax_nonce'),
    ));
}

function dip_wow_action(){
    echo 'ajax ';
    wp_die();
}

add_action('wp_ajax_dip_wow_action', 'dip_wow_action');

dip.js file

function wow(postid,userid){
    var post_id = postid;
    var user_id = userid;

    jQuery.ajax({
        url: dip_url.ajax_url,
        type: 'post',
        data:{
            action: 'wp_ajax_dip_wow_action',
            pid: post_id,
            uid: user_id,
        },
        succes: function( response ){
            
        }

    });
}

Hi there, I have problem with add image using javascript array

I would like add image on web site using javascript array. I found a code then i trying to change. But i can’t get it to work. My code does not display the image on the site.
Code I found:

const imageOut = document.querySelector('.image-out');
for (let key in images) {
    let img = document.createElement('img');
    img.setAttribute('data-key', key);
    img.src = 'images/' + key + '.png';
    imageOut.append(img);
}

html tag: <div class="image-out"></div>
Array:

const images = {"JD-03-128" :{},"JD-05-128": {},"JD-07-128": {},"JD-11-128": {},"JD-12-128": {},"JD-13-128": {},"JD-15-128": {}};

My code:

var imageOut = document.querySelector(".image-out");
for (let key in a) {
    let img = document.createElement('img');
    img.setAttribute('data-key', key);
    img.src = 'image/'+key+'.jpg';
    imageOut.append(img);
}

html tag: <div class="image-out"></div>
Array:

const a = {"a":{},"b":{},"c":{},"d":{},"e":{},"f":{},"g":{}};

image my code: jpg, name absolutely match, name folder absolutely match with folder in my code.
where is my problem ?

How to update data at the same time after an ajax post request

I am doing a ajax post request to

fetch(window.Shopify.routes.root + 'cart/add.js', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(samepleData)
          })
          .then(response => {
            
            return response.json();
            
          })

and after the product has been added to the cart, I open a drawer to show all items in the cart using a GET request to the endpoint

fetch(window.Shopify.routes.root + 'cart.js')
                    .then(response => response.json())
                    .then((cartData) => {
                        console.log(cartData);
                        if(cartData) {
                            
                                showCartDrawer(quick_shop_desktop_container, cartData);
                       
                        }
                    }).catch((err) => {
                        console.log(err);
                    })

and everything is working, it is loading and fetching data, but now once I am in the cart drawer, I have an option to increase quantity and decrease quantity, so everytime someone clicks on increase quanity, it should again make a post request to the first endpoint, and the product will be updated, but the new info will not gonna be shown at the same moment, How to update all the data after the product quantity is increased without refreshing the page and at the same moment? I haven’t woked with this type of conditions before, any guide please?

why is my data undefined? how to access variables inside array

I’m working on a project using the MERN stack. I rertieve an object from the repsonse of my axios request. Inside the object there is an array called items
enter image description here

I need to access the id and title from this array so I can use it in another axios request. When I set items to a const and console.log it displays all the items in the array from the object. However when I console.log items.title or items.id it says that it is undefined. Why is this? How can I access the varaibles inside the array in order to get the id and title.

function Checkout() {
    const [loyalty, setLoyalty] = useState("");
    const currentUser = authService.getCurrentUser();
    const [cartDetails, setCartDetails] = useState([])
    const [total, setTotal] = useState([])
    const history = useHistory();

    const handleChangeLoyalty = ( event ) => {
        setLoyalty(event.currentTarget.value)
    }

    const error = () => {
        message.error('Enter a valid discount');
      };

    useEffect(() => {

        checkout()

    }, [])

    const checkout = () => {
        axios.post("http://localhost:8080/api/getCart", { data: currentUser.id })
            .then((response) => {
                console.log('DATA', response.data.products);
                setCartDetails(response.data.products)
            })
            .catch((err) => {
                console.log(err);
            });
    };

    const items = cartDetails.items
    console.log('ITEMS', items.title)

    const variables = {
        title: cartDetails.items,
        bill: cartDetails.bill,
        userID: currentUser.id
    }

    const createOrder = () => {
        axios.post("http://localhost:8080/api/order/addOrder", { data: variables })
            .then((response) => {
                // console.log('DATA', response.data);
                // setCartDetails(response.data.products)
            })
            .catch((err) => {
                console.log(err);
            });
    };


    const getDiscount = () =>{
        if(loyalty != "NEW10") {
            error()
        }
        else{
            const percent = cartDetails.bill * 0.1
            setTotal(cartDetails.bill - percent)
            console.log(total)
        }
    }

    return (
        <div style={{ width: '75%', margin: '3rem auto' }}>
            <div style={{ textAlign: 'center' }}>
                <h2>  Cart <ShoppingCartOutlined />  </h2>
            </div>


            {cartDetails.length === 0 ?
                <div style={{ display: 'flex', height: '300px', justifyContent: 'center', alignItems: 'center' }}>
                    <h2>Add to your cart</h2>
                </div> :
                <div>
                    <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        {items ? items.map((product, index) => {


                            return <Card
                                // key={index}
                                // productTitle={product.title}
                                hoverable={true}
                            >
                                <Meta
                                    title={product.title}
                                    description={`$${product.price}`}
                                />
                                <DeleteOutlined onClick={deleteFromCart}/>
                            </Card>

                        }) : <div></div>}
                    </Space>


                    <br></br>
                    {total.length === 0 ? <h3>Total: {cartDetails.bill}</h3> : <h3>Total: {total}</h3>} 
                    <p>Input any discount codes below</p>
                    <Input
                        style={{ width: '20%' }}
                        onChange={handleChangeLoyalty}
                        value={loyalty}
                    />
                    <br></br>
                    <Button onClick={getDiscount}>Enter</Button>
                    <br></br>
                    <br></br>
                    <Button onClick={createOrder} size="large" shape="round" icon={<ShoppingCartOutlined />}>BUY</Button>
                    <br></br>
                    <br></br>
                </div>
            }
        </div>
    )
}

export default Checkout;

Hide all hidden mongoose methods and properties

I use nuxt 3. I have this code on my serverside.

  findAuthorByEmail(email: string, showPassword = false) {
    return Author.findOne({ email })
      .select(showPassword ? "" : "-password_hash")
      .lean();
  },

Inside my /server/api/login.post.ts i return it here:

  return {
    token,
    author,
  };

Nuxt has the feature to provide the types for my frontend. How should my query look like so that my response only provides the properties wich are available? If i try to use for example $isDefault then it does not work ofcorse.

Here is also my mongoose model:

import { Document } from "mongoose";
import { AuthorI } from "~~/types";
import { conn } from "../configuration/connection";
import { authorConfig } from "../configuration/author";
import mongoose from "mongoose";
const schema = new mongoose.Schema({
  email: {
    required: true,
    type: String,
    trim: true,
    lowercase: true,
    unique: true,
  },
  password_hash: {
    type: String,
    required: true,
    trim: true,
    minlength: authorConfig.password_min_length,
  },
  name: {
    maxlength: authorConfig.name_length,
    trim: true,
    type: String,
  },
  family_name: {
    type: String,
    maxlength: authorConfig.family_name_length,
    trim: true,
  },
  description: {
    type: String,
    maxlength: authorConfig.description_length,
    trim: true,
  },
  props: {},
  username: {
    type: String,
    trim: true,
    unique: true,
    required: true,
    maxlength: authorConfig.username_length,
  },
  created: {
    type: Date,
    required: true,
    default: Date.now,
    immutable: true,
  },
  enabled: {
    type: Boolean,
    default: true,
  },
});

export const Author = conn.model<AuthorModel>("Author", schema);

interface AuthorModel extends AuthorI, Document {}

![enter image description here

Eslint not work on vscode when format react code

I’m trying to make ESlint work on my vscode but somehow it does not work,

I install ESlint by these step

Step 1

Install them by yarn add eslint --dev

Step 2

The setup then by yarn create @eslint/config

Step 3

Add eslint extension on vscode

enter image description here

But somehow it never work, I tried to have a file like this, but not even show an error, when I run yarn run eslint src/App.js (App.js) is the name, it output like this:

warning ../../package.json: No license field
$ /Users/khanhs/Work/React/Udacity/my-read/node_modules/.bin/eslint src/App.js
✨  Done in 0.47s

.
enter image description here

But the file does not get the format, so what did I do wrong here???