Problem in Typeorm EventSubscriber & Postgres AfterInsert() but entity not inserted

I have a big problem with EventSubscribers of typeorm & postgresSql.

I need to set Notification for a newly created Entity inside AfterInsert event on TypeormEventSubscriber but, when I try to set the relations there is nothing inserted into the database to do that.

# Output of event.entity

Entity: {
  id: 34,
}

# It seems everyting is ok and record inserted but it's not.

Typeorm runs every query including the event hooks query inside a transaction as it seems, until every query is not done correctly, nothing is inserted into the database, which means I can not create relations in that events even in AfterInsertedbecause nothing is written into tables.

there is no other solution for this use case?
I can write the code after entity saved within my service but, not what I’m looking for.

thanks…

TYPEORM:POSTGRESQL Set relations on event hooks

onsubmit function does not invoke correctly using Node.js

I want to make some validations when the form submitted. However when the form submitted validation function seems like invoking correctly. The alert part doesn’t come up but when i try to alert like this

function validation(){
      alert("somethinglol");
      var username = $("#register.username").val().toString();
     
       
       
       alert(username);
     };

somethinglol appears but the second alert doesn’t.

This is my get function:

app.get('/', (req, res) => {
    res.render('index.ejs');
})

This is the index.ejs

<form id="form1" action="/" method="post" onSubmit="validation();">
      <div class="form-group">
        <label for="register.username">Username</label>
        <input type="text" name="username" id="register.username" class="form-control" placeholder="Username" aria-describedby="helpId">
        <small id="helpRegisterUsername" class="text-muted">You should enter a username.</small>
      </div>
      <div class="form-group">
        <label for="register.password">Password</label>
        <input type="password" name="password" id="register.password" class="form-control" placeholder="Password" aria-describedby="helpId">
        <small id="helpId" class="text-muted">Enter a password.</small>
      </div>
      <div class="form-group">
        <label for="register.confirm.password">Confirm password</label>
        <input type="password" name="confirmedPassword" id="register.confirm.password" class="form-control" placeholder="Confirm password" aria-describedby="helpId">
        <small id="helpId" class="text-muted">Confirm password</small>
      </div>
      <input type="submit" id="registerSubmit" value="Submit"></input>

    </form>

This is the script part of index.js which contains the validation() function.

<script>
     function validation(){
      alert($("#register.username").val().toString());
      var username = $("#register.username").val().toString();
      username = "somethinglol";
       
       
       alert(username);
     };
</script>

I have changed the script as external but it didn’t work. I have changed the jquery cdn. I used $("#registerSubmit").click(...) instead of onSubmit but it didn’t work again. I also tried something using async and await but if it’s the problem I am not sure that I did it correctly.

How to dynamically store values from .json file and compare them with user input in python?

I have .json file like this:

[
{
    "name": {
        "common": "Aruba",
        "official": "Aruba",
        "native": {
            "nld": {
                "official": "Aruba",
                "common": "Aruba"
            },
            "pap": {
                "official": "Aruba",
                "common": "Aruba"
            }
        }
    },
    "tld": [
        ".aw"
    ],
    "cca2": "AW",
    "ccn3": "533",
    "cca3": "ABW",
    "cioc": "ARU",
    "independent": false,
    "status": "officially-assigned",
    "unMember": false,
    "currencies": {
        "AWG": {
            "name": "Aruban florin",
            "symbol": "u0192"
        }
    },
    "idd": {
        "root": "+2",
        "suffixes": [
            "97"
        ]
    },
    "capital": [
        "Oranjestad"
    ],
    "altSpellings": [
        "AW"
    ],
    "region": "Americas",
    "subregion": "Caribbean",
    "languages": {
        "nld": "Dutch",
        "pap": "Papiamento"
    },
    "translations": {
        "ces": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "deu": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "est": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "fin": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "fra": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "hrv": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "hun": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "ita": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "jpn": {
            "official": "u30a2u30ebu30d0",
            "common": "u30a2u30ebu30d0"
        },
        "kor": {
            "official": "uc544ub8e8ubc14",
            "common": "uc544ub8e8ubc14"
        },
        "nld": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "per": {
            "official": "u0622u0631u0648u0628u0627",
            "common": "u0622u0631u0648u0628u0627"
        },
        "pol": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "por": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "rus": {
            "official": "u0410u0440u0443u0431u0430",
            "common": "u0410u0440u0443u0431u0430"
        },
        "slk": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "spa": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "swe": {
            "official": "Aruba",
            "common": "Aruba"
        },
        "urd": {
            "official": "u0627u0631u0648u0628u0627",
            "common": "u0627u0631u0648u0628u0627"
        },
        "zho": {
            "official": "u963fu9c81u5df4",
            "common": "u963fu9c81u5df4"
        }
    },
    
{
    "name": {
        "common": "Afghanistan",
        "official": "Islamic Republic of Afghanistan",
        "native": {
            "prs": {
                "official": "u062cu0645u0647u0648u0631u06cc u0627u0633u0644u0627u0645u06cc u0627u0641u063au0627u0646u0633u062au0627u0646",
                "common": "u0627u0641u063au0627u0646u0633u062au0627u0646"
            },
            "pus": {
                "official": "u062f u0627u0641u063au0627u0646u0633u062au0627u0646 u0627u0633u0644u0627u0645u064a u062cu0645u0647u0648u0631u06ccu062a",
                "common": "u0627u0641u063au0627u0646u0633u062au0627u0646"
            },
            "tuk": {
                "official": "Owganystan Yslam Respublikasy",
                "common": "Owganystan"
            }
        }
    },
    "tld": [
        ".af"
    ],
    "cca2": "AF",
    "ccn3": "004",
    "cca3": "AFG",
    "cioc": "AFG",
    "independent": true,
    "status": "officially-assigned",
    "unMember": true,
    "currencies": {
        "AFN": {
            "name": "Afghan afghani",
            "symbol": "u060b"
        }
    },
    "idd": {
        "root": "+9",
        "suffixes": [
            "3"
        ]
    },
    "capital": [
        "Kabul"
    ],
    "altSpellings": [
        "AF",
        "Afu0121u0101nistu0101n"
    ],
    "region": "Asia",
    "subregion": "Southern Asia",
    "languages": {
        "prs": "Dari",
        "pus": "Pashto",
        "tuk": "Turkmen"
    },
    "translations": {
        "ces": {
            "official": "Afghu00e1nsku00e1 islu00e1msku00e1 republika",
            "common": "Afghu00e1nistu00e1n"
        },
        "cym": {
            "official": "Gweriniaeth Islamaidd Affganistan",
            "common": "Affganistan"
        },
        "deu": {
            "official": "Islamische Republik Afghanistan",
            "common": "Afghanistan"
        },
        "est": {
            "official": "Afganistani Islamivabariik",
            "common": "Afganistan"
        },
        "fin": {
            "official": "Afganistanin islamilainen tasavalta",
            "common": "Afganistan"
        },
        "fra": {
            "official": "Ru00e9publique islamique d'Afghanistan",
            "common": "Afghanistan"
        },
        "hrv": {
            "official": "Islamska Republika Afganistan",
            "common": "Afganistan"
        },
        "hun": {
            "official": "Afganisztu00e1ni Iszlu00e1m Ku00f6ztu00e1rsasu00e1g",
            "common": "Afganisztu00e1n"
        },
        "ita": {
            "official": "Repubblica islamica dell'Afghanistan",
            "common": "Afghanistan"
        },
        "jpn": {
            "official": "u30a2u30d5u30acu30cbu30b9u30bfu30f3u00b7u30a4u30b9u30e9u30e0u5171u548cu56fd",
            "common": "u30a2u30d5u30acu30cbu30b9u30bfu30f3"
        },
        "kor": {
            "official": "uc544ud504uac00ub2c8uc2a4ud0c4 uc774uc2acub78c uacf5ud654uad6d",
            "common": "uc544ud504uac00ub2c8uc2a4ud0c4"
        },
        "nld": {
            "official": "Islamitische Republiek Afghanistan",
            "common": "Afghanistan"
        },
        "per": {
            "official": "u062cu0645u0647u0648u0631u06cc u0627u0633u0644u0627u0645u06cc u0627u0641u063au0627u0646u0633u062au0627u0646",
            "common": "u0627u0641u063au0627u0646u0633u062au0627u0646"
        },
        "pol": {
            "official": "Islamska Republika Afganistanu",
            "common": "Afganistan"
        },
        "por": {
            "official": "Repu00fablica Islu00e2mica do Afeganistu00e3o",
            "common": "Afeganistu00e3o"
        },
        "rus": {
            "official": "u0418u0441u043bu0430u043cu0441u043au0430u044f u0420u0435u0441u043fu0443u0431u043bu0438u043au0430 u0410u0444u0433u0430u043du0438u0441u0442u0430u043d",
            "common": "u0410u0444u0433u0430u043du0438u0441u0442u0430u043d"
        },
        "slk": {
            "official": "Afgu00e1nsky islamsku00fd u0161tu00e1t",
            "common": "Afganistan"
        },
        "spa": {
            "official": "Repu00fablica Islu00e1mica de Afganistu00e1n",
            "common": "Afganistu00e1n"
        },
        "swe": {
            "official": "Islamiska republiken Afghanistan",
            "common": "Afghanistan"
        },
        "urd": {
            "official": "u0627u0633u0644u0627u0645u06cc u062cu0645u06c1u0648u0631u06ccu06c1 u0627u0641u063au0627u0646u0633u062au0627u0646",
            "common": "u0627u0641u063au0627u0646u0633u062au0627u0646"
        },
        "zho": {
            "official": "u963fu5bccu6c57u4f0au65afu5170u5171u548cu56fd",
            "common": "u963fu5bccu6c57"
        }
    },
    "latlng": [
        33,
        65
    ],
    "landlocked": true,
    "borders": [
        "IRN",
        "PAK",
        "TKM",
        "UZB",
        "TJK",
        "CHN"
    ],
    "area": 652230,
    "flag": "ud83cudde6ud83cuddeb"
    
}]

I access it through Javascipt code const data = require('./countries.json');. What I need from this .json file is translation keys, for example ces, deu, etc. I need to retrieve them dynamically and store in the array called keys. After that, depending on user’s input, if input is equal to one of the keys from an array it should print official name of all countries using this key.
In my Javascript code I use following methods to do so:

const data = require('./countries.json');
const keys = [];
data.forEach((element) => {
Object.keys(element.translations).forEach((item) => {
keys.push(item);
}) ;
});

/**
*Removes all duplicate translation keys
*@param {1} keys of translation keys
*@return {unique} a unique array of translation keys
*/
function removeDuplicates (keys) { 
const unique = [];
      keys.forEach((element) => {
if (!unique.includes(element)) {
  unique.push(element);
}
});
return unique;
}
const enteredKey = process.argv.slice(2);
console.log('Key is : ', enteredKey);

if (enteredKey.length < 2 && enteredKey !== null && removeDuplicates(keys).includes(enteredKey[0])) {
try {
for (const {translations} of data) {
  const key = translations[enteredKey]?.official;
  if (key) {
    console.log(key);
  }
 }
}

Please note that I am using const key = translations[enteredKey]?.official; because there are a lot of countries and few of them do not have some keys, like cym key is appear in only half of the countries. Without [enteredKey]?.official program will crush because it won’t be able to find this key and define it.

Now I need to the same, but with python3. I have tried :

f = open('./countries.json')
translationKeys = json.load(f)
keys = []
for i in translationKeys[0]["translations"]:
keys.append(i)
print(keys)
f.close()

but the output was really messy:

['ces']
['ces', 'deu']
['ces', 'deu', 'est']
['ces', 'deu', 'est', 'fin']

Since I am not familiar with python at all, I am curious how to retrieve and store these keys the same way I did that in Javascript and print value of these keys depend on user’s input.
I will leave a github link for those who wish to see entire project to get more context if needed: https://github.com/TheRadioDept/technical-question

Input is not cleared when working with e.target

I can’t figure out what’s going on. Below is the JS code that is responsible for closing and opening the search box running in the JS application. Closing occurs by pressing a button with a cross, Esc keyboard and anywhere in this window


const btn = document.querySelector('.head__search-icon'),
body = document.body,
search = document.querySelector('.search'),
searchInner = document.querySelector('.search__inner'),
searchOverlay = document.querySelector('.search__overlay'),
searchInput = document.querySelector('#search__input'),
btnClose = document.querySelector('.search__closed-button');
body.classList.add('no-search'),
search.style.display = 'none';


function searchOpen() {
btn.addEventListener('click', () => {
    body.classList.remove('no-search');
    body.classList.add('is-search');
    search.style.display = 'block';
    setTimeout(() => searchInput.focus(), 100);
    if (body.classList.contains('is-head-open')) {
        body.classList.remove('is-head-open');
    }
});
}
searchOpen();

function searchClose() {
    body.classList.add('no-search');
    body.classList.remove('is-search');
    searchInput.value = '';
    searchInput.blur();

}

function searchRemove(e) {
    if(e.code === "Escape" && body.classList.contains('is-search') || e.target === searchOverlay || e.target === searchInner) {
        searchClose();
    }
}

document.addEventListener('keydown', searchRemove);
search.addEventListener('click', searchRemove);
btnClose.addEventListener('click', searchClose);


The fact is that if there is a search result, and press Esc, then everything works, the focus from the input disappears, and the input itself is cleared. But if you click anywhere in the window ( e.target === searchOverlay || e.target === searchInner ), then the window itself closes, the input is cleared, as I need, except that with a visually clean input, the search results remain. That is, you open the window again and see the same search results, although the input is empty. When working with Esc, the input is actually cleared. Where is the jamb in the script?

ViewChild is undefined in angular 13

I am trying to call view child of a child component from parent and getting undefined in the console.

see the image also see the stack blaze for the same

https://stackblitz.com/edit/angular-ivy-k4m2hp?file=src%2Fapp%2Fhello.component.ts

see the image also see the stack blaze for the same

import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { TestChildComponent } from './test-child/test-child.component';

@Component({
  selector: 'hello',
  template: `<h1>this is Hello component {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
  @Input() name: string;
@ViewChild('TestChildComponent') testChildComponent: TestChildComponent
  ngOnInit() {
    console.log('calling ngOninit in hello component');
    console.log('going to call test child instance this.TestChildComponent.ngOninit')
   console.log(this.testChildComponent);
  }
}

Please help to get the child component

this.testChildComponent

So that i can call ngOnInit of child from parent.

How to get all the children in an javascript object

I am trying to getting the data from the api and have to set the children for all the parent elements. This is the thing I need to do. For more details see below.

I am having an javascript object as this.

var data = [
    {
        "id": "1",
        "name": "India"
    },
    {
        "id": "2",
        "name": "TamilNadu",
        "parentId": "1"
    },
    {
        "id": "3",
        "name": "Chennai",
        "parentId": "2"
    },
    {
        "id": "4",
        "name": "Trichy",
        "parentId": "2"
    },
    {
        "id": "5",
        "name": "Kerala",
        "parentId": "1"
    },
    {
        "id": "6",
        "name": "Kochi",
        "parentId": "5"
    }
];

and I need output as this

[
    {
        "id": "1",
        "name": "India",
        "children": [
            {
                "id": "2",
                "name": "TamilNadu",
                "parentId": "1",
                "children": [
                    {
                        "id": "3",
                        "name": "Chennai",
                        "parentId": "2"
                    },
                    {
                        "id": "4",
                        "name": "Trichy",
                        "parentId": "2"
                    }
                ]
            },
            {
                "id": "5",
                "name": "Kerala",
                "parentId": "1",
                "children": [
                    {
                        "id": "6",
                        "name": "Kochi",
                        "parentId": "5"
                    }
                ]
            }
        ]
    }
]

Note: The “data” object is not static. This may be dynamic like one parent can have thousand of children and grandchildren

Please help me on this and thank in advance.

Navbar in nextjs keeps opening the home page even though the slug specified is different and the dynamic routing is implemented

import Link from 'next/link';
import React, { useState } from 'react';
import { tabs } from '../public/data/nav.js';

const Tabs = () => {
  const [activeTab, setActiveTab] = useState(tabs[0].id);

  return (
    <div className='container flex flex-row justify-start min-w-full mx-auto bg-slate-900'>
      <div className='container flex flex-row items-center justify-start max-w-fit'>
        {/* Tab nav */}
        {tabs.map((tab) => (
          <Link href={tab.slug} key={tab.id}>
            <a
              className={`px-20 py-4 border-r-[1px] border-slate-300/40 ${
                activeTab === tab.id
                  ? 'bg-slate-800 border-t-[2px] border-t-rose-600 text-amber-500'
                  : 'border-t-[1px] border-b-[1px] border-slate-300/40 '
              } `}
              onClick={() => setActiveTab(tab.id)}
            >
              {tab.name}
            </a>
          </Link>
        ))}
      </div>
      <div className='min-w-full border-y-[1px] border-slate-300/40'></div>
    </div>
  );
};
export default Tabs;

I’ve implemented client-side routing using <Link /> provided by NextJS. The data comes from here

export const tabs = [
  {
    id: 0,
    name: '_hello',
    slug: '/',
    title: '',
  },
  {
    id: 1,
    name: '_about_me',
    slug: '/about',
    title: 'about',
  },
  {
    id: 2,
    name: '_projects',
    slug: '/projects',
    title: 'projects',
  },
];

But time to time I open up a specific route, let’s /about, or just when I open a site in a new tab, it brings me to the home page even though the slug would be a right one, for example /about.

Why is it happening?

AJAX call to async Task in MVC

I am trying to make an aJax Call (View-side) to an async Task<> function on the Controller-side and returning the result back to the ajax call for some other functions later on.

Controller Snippet

using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

    public class DataController : Controller
    {
        private UserManager<AppUser> _userManager { get; }
        private SignInManager<AppUser> _signInManager { get; }
        public CSVController(SignInManager<AppUser> signInManager, UserManager<vFarmAppUser> userManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        public async Task<ActionResult> RetrieveDataAsync(string time)
        {
            var count = 0;
            using (var context = new DataDbContext())
            {
                proxyRecords = context.Datas.ToList();
                count = proxyRecords.Count();
            }

            var userId = this.User.FindFirstValue(ClaimTypes.Name);
            Console.WriteLine(userId);
            AppUser user = await _userManager.FindByNameAsync(userId);

            var metaHolder = new ModelClass
            {
                UniqueId = 1000,
                dataTime = time,
                RecordNo = count,
                Topic = user.Topic
            };
            Console.WriteLine(metaHolder);
            return Json(metaHolder);
        }
    }

View Snippet

<div style="width: 100%; width: 1100px; background-color: none">
    <div>
        <button id="btnSave" class="btn btn-primary">Save Data</button>
    </div>
</div>    
@section Scripts
{
    <script type="text/javascript">
    
        $(document).ready(function () {
            Init();
        });

        function Init() {
            _oRecord = [];
            _metaData = [];

            $("#btnSave").click(function () {
                $.ajax({
                    url: '../Data/RetrieveProxy/',
                    cache: false,
                    dataType: "json",
                    success: function (result) {
                        _oRecords = result;
                    },
                });

                var d = new Date();
                var getDate = [d.getFullYear(), d.getMonth(), d.getDay()].map((a) => (a < 10 ? '0' + a : a));
                var getJoinedDate = getDate.join(':');
                var getTime = [d.getHours(), d.getMinutes(), d.getSeconds()].map((a) => (a < 10 ? '0' + a : a));
                var getJoinedTime = getTime.join(':');
                var getDateTime = getJoinedDate + "-" + getJoinedTime;
                $.ajax({
                    url: '../Data/RetrieveDataAsync/',
                    data: { time: getDateTime },
                    cache: false,
                    async: false,
                    contentType: "application/json",
                    processData: false,
                    success: function (result) {
                        _metaDatas = result;
                        alert(JSON.stringify(_metaDatas));
                    },
                    error: function (error) {
                        alert(error.statusText);
                    }
                });
            });
        };
    </script>
}

Currently, the 1st ajax call to /Data/RetrieveProxy/ works perfectly fine but the 2nd ajax call does not work. I was trying to solve it by following this Post but to no avail, unfortunately.

How do I make this into 4 column in one row and also responsive as well?

I have this Grid and Card where I wanted to make it into 4 columns in one row. Currently, the 4th column goes in the 2nd row, like this:
enter image description here

I wanted to put the 4 columns in one row.

Also, if it’s on a small screen, why does it look like this? The columns are not arranged.

enter image description here

codesandbox link: https://codesandbox.io/s/4-boxes-in-one-row-0mym3j?file=/demo.js

Codes:

 <Container style={{ marginTop: "1rem", marginBottom: "1rem" }}>
      <Box sx={{ "& h1": { m: 0 } }}>
        <Grid container spacing={2} justify="flex-start">
          <Grid item xs={12} sm={6} md={4}>
            <Card>
              <CardContent>
                <Stack direction="row" spacing={2}>
                  <Typography variant={"h6"} gutterBottom>
                    Column 1
                  </Typography>
                </Stack>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} sm={6} md={4} order={{ xs: 3, sm: 2 }}>
            <Card>
              <CardContent>
                <Stack direction="row" spacing={2}>
                  <Typography variant={"h6"} gutterBottom>
                    Column 2
                  </Typography>
                </Stack>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} sm={6} md={4} order={{ xs: 2, sm: 3 }}>
            <Card>
              <CardContent>
                <Stack direction="row" spacing={2}>
                  <Typography variant={"h6"} gutterBottom>
                    Column 3
                  </Typography>
                </Stack>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} sm={6} md={4} order={{ xs: 2, sm: 3 }}>
            <Card>
              <CardContent>
                <Stack direction="row" spacing={2}>
                  <Typography variant={"h6"} gutterBottom>
                    Column 4
                  </Typography>
                </Stack>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Box>
    </Container>

Kendo Editor Dynamic Link onClick Function Not Working

I have a custom toolbar which inserts a link in kendo editor. I am trying to put a onClick function in that link but when the dynamically inserted link is clicked it says function is not defined. I also tried it by putting a class on that link and have a click function to that class but it does not get hit.

Any help would be much appreciated.

$("toolbarSubmitBtn").("click", function () {
    var value = $("toolbarInput").val();

    var $html = '<a onClick="myFunction()"> Click to show alert </a>';
    //var $html = '<a class="functioncall"> Click to show alert </a>';
    var $empty = $("<div>").append($html)
    $("#editor").data("kendoEditor").paste($empty.html());
});

Class Call

$(document).on("click", ".functioncall", function () {
    alert("function called from class");
});

Function Call

function myFunction() {
    alert("function called by click");
}

How to list 4 products on every page using ant design Pagination component in react js?

How to list 4 products on every page using ant design Pagination component in react js?
Here is details:
I actually want to display 4 products on every page using ant design pagination. I have code that works correctly. (i.e in the begining 4 products display on every page). But there is one issue. I have search and filteration as well in that component. When I search a product, if I found more than 4 products, that display on a single page but I want that after search if there are more than 4 products found then 4 products shown on every page as well. Please help me. I have tried my best but not get correct solution.

Here is my data.js file:

export const data = [
    {
      logo: "",
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681c6e998744",
      category: "Biotech",
      manufacturer: "Johanson & Johanson (PVT) LTD",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998755",
      category: " Health",
      manufacturer: "Talha",
      active: "Minoxidil:10%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998766",
      category: " Health",
      manufacturer: "David",
      active: "Minoxidil:15%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998777",
      category: " Health",
      manufacturer: "saad",
      active: "Minoxidil:125%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Fashion",
      id: "681cc76998788",
      category: "Health",
      manufacturer: "Fahad",
      active: "Minoxidil:95%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998799",
      category: "ABC",
      manufacturer: "ABC",
      active: "Minoxidil:25%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "68",
      category: "electronic",
      manufacturer: "Awais",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681c",
      category: " Electric",
      manufacturer: "musa",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
      link: "GNC",
      id: "681cc76e992222",
      category: " GNC supplements, Proteins and Supplements",
      manufacturer: "Johanson & Johanson (PVT) LTD",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
      link: "XYZ",
      id: "681cc76e9983333",
      category: " XYZ",
      manufacturer: "XYZ",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      link: "EFG",
      id: "681cc76e99744444",
      category: "EFG",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "HIJ",
      id: "1",
      category: "HIJ",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "KLM",
      id: "12",
      category: "KLM",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "NOP",
      id: "123",
      category: "NOP",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "QRS",
      id: "1234",
      category: "QRS",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "TUV",
      id: "123456",
      category: "TUV",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  ];
  

Here is my Searching.js component code:

import React, { useState } from "react";
import "./searching.css";
import { data } from "./data";
import { FilterOutlined } from "@ant-design/icons";
import {
  Typography,
  Space,
  Card,
  Button,
  Tree,
  Input,
  Pagination,
  Empty,
  Modal,
} from "antd";

const Searching = () => {
  const { Text, Title, Link } = Typography;
  const { Search } = Input;
  
   // dynamic data
  const [maindata, setMainData] = useState(data?.slice(0, 4));

  // search filteration states
  const [search, setSearch] = useState("");
  const exculdeData = [
    "id",
    "logo",
    "link",
    "category",
    "drug_strength",
    "drug_form",
    "pack_size",
  ];

  // pagination states
  const [number, setNumber] = useState(1);
  const [postsPerPage] = useState(4);
//   handle Pagination
  const handlePage = (pageNumber) => {
    console.log(pageNumber);
    setNumber(pageNumber);

    const indexOfLastPost = pageNumber * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = data?.slice(indexOfFirstPost, indexOfLastPost);
    setMainData(currentPosts);
  };
//   handle search change
  const handleChange = (value) => {
    setSearch(value);
  };
  
   //   click on search button to trigger it
  const onSearch = (value) => {
    const lowerCaseValue = value.toLowerCase().trim();
    if (!lowerCaseValue) {
      setMainData(data);
    } else {
      const filterSearch = data.filter((item) => {
        // console.log(Object.keys(item));
        return Object.keys(item).some((key) => {
          // console.log(key);
          return exculdeData.includes(key)
            ? false
            : item[key].toString().toLowerCase().includes(lowerCaseValue);
        });
      });
      // consoleFun(filterSearch)
      setMainData(filterSearch);
    }
  };
  
   return (
    <div>
      <div style={{ width: "90%" }}>
        <div className="banner">
          <Text>
            <Title level={3} className="search_title">
              Search Products
            </Title>
          </Text>
          <Text>
            <Title level={5}>
              Find numerous unregistered products that can fulfill you need
            </Title>
          </Text>
        </div>
        <div className="main_container">
          {/* for search */}
         

          <div>
            <Search
              enterButton="Search"
              size="large"
              placeholder="Search Product"
              className="search_bar"
              onSearch={onSearch}
              onChange={(e) => handleChange(e.target.value)}
            />
          </div>
         
        </div>
        {/* for showing result */}
        <div className="showing_result">
          <div className="filter_search">
            <Text>Showing results for {`"${search} "`}</Text>
          </div>{" "}
          <div className="filter_result">
            <Text>
              showing {number}-{postsPerPage} of {data?.length} results
            </Text>
          </div>
        </div>

        {/* for showing cards data */}
        {maindata.length ? (
          maindata.map((item) => {
            const {
              logo,
              link,
              id,
              category,
              manufacturer,
              active,
              drug_strength,
              drug_form,
              pack_size,
            } = item;
            return (
              <div key={id} className="carrd">
                <Card>
                  <div className="card_container">
                    <div>
                      <img
                        src="https://picsum.photos/200/300"
                        alt="product image"
                        className="cards_img"
                      />
                      
                    </div>
                    <Space direction="vertical" className="card_data">
                      <img src="" alt="Logo" />
                      <Text>
                        <Link>
                          <strong className="card_link">{link}</strong>
                        </Link>
                      </Text>
                      <Text type="secondary">
                        Product ID: <Text>{id}</Text>
                      </Text>

                      <Text type="secondary">
                        Category:
                        <Text className="blue_text">{category}</Text>
                      </Text>

                      <Text type="secondary">
                        Manufecture:{" "}
                        <Text className="blue_text">{manufacturer}</Text>
                      </Text>

                      <Text type="secondary">
                        Active Pharmaceutical Ingredients:{" "}
                        <Text className="blue_text">{active}</Text>
                      </Text>

                      <Text type="secondary">
                        Drug Strength: <Text>{drug_strength}</Text>
                      </Text>

                      <Text type="secondary">
                        Drug Form: <Text>{drug_form}</Text>
                      </Text>

                      <Text type="secondary">
                        Pack Size: <Text>{pack_size}</Text>
                      </Text>
                      <Space className="buttons">
                        <Space>
                          <Button type="primary">View Details</Button>
                          <Button style={{ background: "green" }}>
                            Send RFI
                          </Button>
                        </Space>
                      </Space>
                    </Space>
                  </div>
                </Card>
              </div>
            );
          })
        ) : (
          <div className="empty_container">
            <div>
              <Empty description={false} className="empty_data">
                No Product Found
              </Empty>
            </div>
          </div>
        )}
        <div className="pagination">
          {maindata?.length == 0 ? null : search?.length ? (
            <Space>
              <Pagination
                defaultCurrent={number}
                total={maindata?.length}
                defaultPageSize={postsPerPage}
                onChange={handlePage}
              />
            </Space>
          ) : (
            <Space>
              <Pagination
                defaultCurrent={number}
                total={data?.length}
                defaultPageSize={postsPerPage}
                onChange={handlePage}
              />
            </Space>
          )}
        </div>
      </div>
    </div>
  );
};

export default Searching;

According to doctors name (dropdown) and date selected ,change timeslot dropdown using AJAX in django

//This is my book_appoint.html
<!DOCTYPE html> <html>
 <div class="wrapper"> 
<div class="register-page">
 <div class="register-container"> 
<form id="appointment-form" role="form" method="post" enctype='multipart/form-data'>

<!-- SECTION TITLE -->
      <div class="section-title wow fadeInUp" data-wow-delay="0.4s">
           <h2>Book Appointment</h2>
      </div>
      {% csrf_token %}
      <input name="patient_name" value="{{request.user}}" hidden> 
      <div class="wow fadeInUp" data-wow-delay="0.8s">
           

           <div class="col-md-6 col-sm-6">
                <label for="qualification">Doctor Name</label>
                {{ form.doctor_name }}
           </div>

           <div class="col-md-6 col-sm-6">
                <label for="specialist"> Date</label>
                {{ form.date }}
           </div>
           

           <div class="col-md-6 col-sm-6">
                <label for="location">Time slot </label>
                {{ form.time_slot }}   // want to apply ajax to select available slot only
           </div>
           

           <div class="col-md-12 col-sm-12">
                <label for="description"> Description</label>
                {{ form.description }}
                <br>
                <button type="submit" class="submitButton" id="cf-submit" name="submit">Submit Button</button>
           </div>
      </div>
</form>
</div> </div> </div>

</html>

//This is my view file:

def book_appointment(request):
    if request.method == 'POST':
        form = BookAppointmentForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            patient_name = request.POST.get('patient_name')
            patient = form.save(commit=False)
            patient.patient_name = User.objects.get(username=patient_name)



            
            form.save()
            messages.success(request, 'appointment booked Successfully')
            return redirect(homepage)
        else:
            form = BookAppointmentForm()
            messages.error(request, 'Please Enter valid Request ')
            print(form)
            return render(request, 'book_appointment.html', {'form': form})
    else:
        form = BookAppointmentForm()
        return render(request, 'book_appointment.html', {'form': form})

//Here is my models:

class BookAppointment(models.Model):
    TIME_SLOT = (
        (0, '09:00 - 10:00'),
        (1, '10:00 - 11:00'),
        (2, '11:00 - 12:00'),
        (3, '12:00 - 13:00'),
        (4, '13:00 - 14:00'),
        (5, '14:00 - 15:00'),
        (6, '15:00 - 16:00'),
        (7, '16:00 - 17:00'),
        (8, '17:00 - 18:00'),
    
    )
    doctor_name=models.ForeignKey(User, on_delete=models.CASCADE,related_name="doctor_name")
    patient_name=models.ForeignKey(User, on_delete=models.CASCADE,related_name="patient_name")
    description=models.TextField(blank = True)
    date=models.DateField(help_text="DD-MM-YYYY")
    time_slot= models.IntegerField(choices=TIME_SLOT)

    class Meta:
        ordering = ('date', 'time_slot')
        unique_together = (
            ('doctor_name', 'date', 'time_slot'),  

    def __str__(self):
        return '{} {} {}. Patient: {}'.format(self.date, self.time_slot, self.doctor_name, self.patient_name)

I have already post this form and it store values simple in database.But I have not used Ajax , which I want to apply here, when user select particular doctor name from dropdown and after that user select dates from calendar, through Ajax it should be able to select available Timeslots, and also disable timeslots which are already booked(unavailable).

How to check an array for a value before pushing a value into that array using mongoose and mongodb

I currently have a Post model where a post has a “likes” array where I store the user_id of the user who liked the post. I want these to be unique so that a user cannot like a post more than once. When updating the Post with the like I’m having a hard time validating whether or not the user is in the array. The following is what I have set up so far.

postRouter.put('/:postId/like', (req, res, next) => {
  Post.findByIdAndUpdate(
    { _id: req.params.postId},
    { $push: { likes: req.user._id } },
    { new: true },
    (err, updatedPost) => {
      if (err) {
        res.status(500);
        return next(err);
      }
      return res.status(200).send(updatedPost);
    }
  );
});

and my model:

postSchema ({
   ...,
   likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
})

Serving static files from Express server

I have an Express server that contains a public folder containing 5 images. I want to load those images inside of my ReactJS app. How would I do that?

I’m already using:

app.use("/static", express.static(path.join(__dirname, "public")));

and I can access them when I manually type in the URL, but I’m unable to figure out how to serve them all in my React app.

Any help would be much appreciated.