How to show API options in Autocomplete and update them

I’m trying to update a autocomplete options, but when I try to remove a selected tag (de select) or choose new tag (select) I get this warning in my console log:

MUI: The value provided to Autocomplete is invalid. None of the
options match with
[{"catName":{"catName":"rfbsdrfbertherth"}},{"catName":{"catName":"sfnojblkigpsm"}},{"catName":{"catName":"jkflnbr.efb"}}].
You can use the isOptionEqualToValue prop to customize the equality
test.

Also this error:

Uncaught Error: Objects are not valid as a React child (found: object
with keys {catName}). If you meant to render a collection of children,
use an array instead.

In my Autocomplete component SelectPostsCatsOptions I’m fetching the options from API:

export default function SelectPostsCatsOptions({onBlur, selectedCategories, setSelectedCategories, readOnly, value, onChange}) {

    const [postsCats, setPostsCats] = useState([]);
    const [loading, setLoading] = useState(true);

    // FETCH THE CATEGORIES FROM THE DATABASE
    useEffect(() => {
        const getPostsCats = async () => {
          const res = await axios.get("/postscategories");
          setPostsCats(res.data);
          setLoading(false);
        };
        getPostsCats()
      }, []);
    // END OF FETCH THE CATEGORIES FROM THE DATABASE

    return (

        <div>
            <Autocomplete
              readOnly={readOnly}
              multiple
              disablePortal
              id="postsCats"
              getOptionLabel={(postsCats) => `${postsCats.catName}`}
              options={postsCats}
              isLoading={loading}
              loadingText="Loading categories..."
              maxWidth={false}
              disableGutters
              isOptionEqualToValue={(option, value) => option.catName === value.catName}
              noOptionsText={"No Available Options"}
              renderOption={(props, postsCats) => (
                <li 
                  {...props} 
                  key={postsCats.id}
                  style={{ …}}>
                  {postsCats.catName}
                </li>
                )}
                value={value}
                // THE TAGS SELECTED
                renderTags={(value, getTagProps) =>
                  value.map((option, index) => (
                    <Chip
                      key={option.id}
                      label={option.catName}
                      {...getTagProps({ index })}
                      style={{…}}
                    />
                  ))
                }
                // END OF THE TAGS SELECTED
                renderInput={(params) => <TextField
                    readOnly={readOnly}
                    {...params}
                    placeholder="Categories"
                    InputLabelProps={{ …} }}
                    sx={{…}}
                      // THE RIGHT END ICON
                      InputProps={{
                        style: { … },
                        ...params.InputProps,
                        endAdornment: (
                            <React.Fragment>
                                {loading ? <CircularProgress /> : null}
                                {params.InputProps.endAdornment}
                            </React.Fragment>
                        ),
                    }}
                    // END OF THE RIGHT END ICON
                    /> }
                    onChange={onChange}
            />          
        </div>
        
    );
}

Then i’m using the Autocomplete here is this page (form).

import SelectPostsCatsOptions from "../../components/autocomplete/SelectPostsCatsOptions";

export default function PostInfo() {

    const [categories, setCategories] = useState([]);
    const [selectedCategories, setSelectedCategories] = useState([]);
    const [postInfoPageUpdateMode, setPostInfoPageUpdateMode] = useState(false);

    // TO FETCH DATA FROM THE DATABASE
    useEffect(() => {
      // TO FETCH POST
      const getPost = async () => {
        try {
          const res = await axios.get("/posts/" + path);
          setPost(res.data);
          setCategories(res.data.categories);
          setIsLoading(false);
          console.log("Post:", res.data);
        // HANDLING ERROR
        } catch (err) {
          setIsLoading(false);
        }
        // END OF HANDLING ERROR
        };
        getPost()
      }, [path]);
    // END OF TO FETCH DATA FROM THE DATABASE

    // HANDLE THE DATA TO SUBMIT
    const handleUpdate = async () => {
      if (!title || !content || !photo ) {
        setAlertMsg({ fail: true, success: false, msg: "All fields are required!" });
        return;  
      } else try {
          await axios.put(`/posts/${post._id}`, {
            username:user.username, 
            categories: selectedCategories.map(cat => cat.catName),
          });
          window.location.reload();
          setPostInfoPageUpdateMode(false);

      // HANDLING ERROR
      } catch (err) {

      }
      // END OF HANDLING ERROR
    };
    // END OF HANDLE THE DATA TO SUBMIT


  return (
    // // POST INFO PAGE
    <div className="PostInfoPage">

      {/* IF THE PAGE IS LOADING SHOW CIRCULAR PROGRESS */}
      {isLoading ? (
            ………
      ) : (
        <>
      {/* POST VIEW OR EDIT CONTAINER */}
      <div className="PostInfoPageBottom" dir="auto">
        {/* POST FORM */}
        <form className="PostInfoPageForm" dir="auto">
                {/* POST CATEGORIES CONTAINER */}
                <div className="PostInfoPagePostContentContainer">
                    <h3>Post Categories:</h3>
                      <SelectPostsCatsOptions
                        selectedCategories={selectedCategories} 
                        setSelectedCategories={setSelectedCategories}
                        readOnly={postInfoPageUpdateMode ? false : true}
                        value={selectedCategories.map((catName) => ({ catName }))}
                        onChange={(event, newSelectedCategories) => setSelectedCategories(newSelectedCategories)}
                      />
                </div>
                {/* END OF POST CATEGORIES CONTAINER */}
        </form>
        {/* END OF POST FORM */}
      </div>
      {/* END OF POST VIEW OR EDIT CONTAINER */}
      </>
      )}
      {/* END OF IF THE PAGE IS LOADING SHOW CIRCULAR PROGRESS */}
    </div>
    // // END OF POST INFO PAGE
  );
}

The autocomplete here should show the options chosen from the API (post.categories), which i’m value for it, but the issue is when changing (updating) these options, I don’t know if it’s from onChange or something else ! What I’m trying to implement is:

  1. show the options (Array) back from API (post.categories)
  2. update the options (de-select or select new option)
  3. update the option in the API, which i’m using handleUpdate for it

define dynamic key in initialState in redux

I have a e-commerce website and every user has shopping cart and handle this with redux and redux persist to store in local storage. I want to handle multiple account in one computer and If a user has two account he can switch between account and and the data related to each account get shown, my problem is how to handle multi account on one system , each account has id. I want to define this structure for initial state:

 const initialState = {
    [userId]:{
        cart:[]
  }

but I got error

for login I handle this with next-auth and I define this reducer for get Id as user log in.

addUserId: async (state, action) => {   //here I receive userId
      const session = await getSession();
      console.log(session);
    },

If user is not authenticated and adding something to cart, the item goes to the wishlist. But if user is logged in everything ok. DJANGO JS

I want my system to remember not only the products of logged in people, but also those who are not logged in. I made about the same cookie system for cart and wishlist that works until you loogged out. I’ll put everything because idk where exactly to look

main.html script part

<script type="text/javascript">
        var user = '{{request.user}}'

        function getToken(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        var csrftoken = getToken('csrftoken')

        function getCookie(name) {
            var cookieArr = document.cookie.split(";");

            for(var i = 0; i < cookieArr.length; i++) {
                var cookiePair = cookieArr[i].split("=");

                if(name == cookiePair[0].trim()) {
                    return decodeURIComponent(cookiePair[1]);
                }
            }

            return null;
        }
        var cart = JSON.parse(getCookie('cart'))

        if (cart == undefined){
            cart = {}
            console.log('Cart Created!', cart)
            document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
        }
        console.log('Cart:', cart)

        var wishlist = JSON.parse(getCookie('wishlist'))

        if (wishlist == undefined){
            wishlist = {}
            console.log('wishlist Created!', wishlist)
            document.cookie ='wishlist=' + JSON.stringify(wishlist) + ";domain=;path=/"
        }
        console.log('Wishlist:', wishlist)

cart.html (wishlist almost the same)

{% extends 'store/main.html' %}
{% load static %}
{% block content %}
    <div class="row">
        <div class="col-lg-12">
            <div class="box-element">

                <a  class="btn btn-outline-dark" href="{% url 'store' %}">&#x2190; Continue Shopping</a>

                <br>
                <br>
                <table class="table">
                    <tr>
                        <th><h5>Items: <strong>{{order.get_cart_items}}</strong></h5></th>
                        <th><h5>Total:<strong> {{order.get_cart_total|floatformat:0}}₽</strong></h5></th>
                        <th>
                            <a  style="float:right; margin:5px;" class="btn btn-dark" href="{% url 'checkout' %}">Checkout</a>
                        </th>
                    </tr>
                </table>

            </div>

            <br>
            <div class="box-element">
                <div class="cart-row">
                    <div style="flex:2"></div>
                    <div style="flex:2"><strong>Item</strong></div>
                    <div style="flex:1"><strong>Color</strong></div>
                    <div style="flex:1"><strong>Size</strong></div>
                    <div style="flex:1"><strong>Sex</strong></div>
                    <div style="flex:1"><strong>Price</strong></div>
                    <div style="flex:1"><strong>Quantity</strong></div>
                    <div style="flex:1"><strong>Total</strong></div>
                </div>
                {% for item in items %}
                <div class="cart-row">
                    <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div>
                    <div style="flex:2"><p>{{item.product.name}}</p></div>
                    <div style="flex:1"><p>{{item.product.color}}</p></div>
                    <div style="flex:1"><p>{{item.product.size}}</p></div>
                    <div style="flex:1"><p>{{item.product.sex}}</p></div>
                    <div style="flex:1"><p>{{item.product.price|floatformat:0}}₽</p></div>
                    <div style="flex:1">
                        <p class="quantity">{{item.quantity}}</p>
                        <div class="quantity">
                            <img data-product="{{item.product.id}}" data-action="add" class="chg-quantity update-cart" src="{% static  'images/arrow-up.png' %}">
                    
                            <img data-product="{{item.product.id}}" data-action="remove" class="chg-quantity update-cart" src="{% static  'images/down-arrow.png' %}">
                        </div>
                    </div>
                    <div style="flex:1"><p>{{item.get_total|floatformat:0}}₽</p></div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
{% endblock content %}

cart.js

var updateBtns = document.getElementsByClassName('update-cart')

for (i = 0; i < updateBtns.length; i++) {
    updateBtns[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)
        console.log('USER:', user)

        if (user == 'AnonymousUser'){
            addCookieItem(productId, action)
        }else{
            updateUserOrder(productId, action)
        }
    })
}

function updateUserOrder(productId, action){
    console.log('User is authenticated, sending data...')

        var url = '/update_item/'

        fetch(url, {
            method:'POST',
            headers:{
                'Content-Type':'application/json',
                'X-CSRFToken':csrftoken,
            }, 
            body:JSON.stringify({'productId':productId, 'action':action})
        })
        .then((response) => {
           return response.json();
        })
        .then((data) => {
            location.reload()
        });
}

function addCookieItem(productId, action){
    console.log('User is not authenticated')

    if (action == 'add'){
        if (cart[productId] == undefined){
        cart[productId] = {'quantity':1}

        }else{
            cart[productId]['quantity'] += 1
        }
    }

    if (action == 'remove'){
        cart[productId]['quantity'] -= 1

        if (cart[productId]['quantity'] <= 0){
            console.log('Item should be deleted')
            delete cart[productId];
        }
    }
    console.log('CART:', cart)
    document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
    
    location.reload()
}

wishlist.js (almost the same)

var updateBtns = document.getElementsByClassName('update-wishlist')

for (i = 0; i < updateBtns.length; i++) {
    updateBtns[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)
        console.log('USER:', user)

        if (user == 'AnonymousUser'){
            addCookieItem(productId, action)
        }else{
            updateUserWish(productId, action)
        }
    })
}

function updateUserWish(productId, action){
    console.log('User is authenticated, sending data...')

        var url = '/update_wish_item/'

        fetch(url, {
            method:'POST',
            headers:{
                'Content-Type':'application/json',
                'X-CSRFToken':csrftoken,
            },
            body:JSON.stringify({'productId':productId, 'action':action})
        })
        .then((response) => {
           return response.json();
        })
        .then((data) => {
            location.reload()
        });
}

function addCookieItem(productId, action){
    console.log('User is not authenticated')

    if (action == 'add'){
        if (wishlist[productId] == undefined){
        wishlist[productId] = {'quantity':1}

        }else{
            if wishlist[productId]['quantity'] == 1:
                wishlist[productId]['quantity'] += 0
        }
    }

    if (action == 'remove'){
        wishlist[productId]['quantity'] -= 1

        if (wishlist[productId]['quantity'] <= 0){
            console.log('Item should be deleted')
            delete wishlist[productId];
        }
    }
    console.log('WISHLIST:', wishlist)
    document.cookie ='wishlist=' + JSON.stringify(wishlist) + ";domain=;path=/"

    location.reload()
}

models.py for orders and wishes:

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)
    transaction_id = models.CharField(max_length=100, null=True)

    def __str__(self):
        return str(self.id)
        
    @property
    def shipping(self):
        shipping = False
        orderitems = self.orderitem_set.all()
        for i in orderitems:
            if i.product.status == True:
                shipping = True
        return shipping

    @property
    def get_cart_total(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.get_total for item in orderitems])
        return total 

    @property
    def get_cart_items(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.quantity for item in orderitems])
        return total


class Wish(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    date_wished = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)

    def __str__(self):
        return str(self.id)

    @property
    def get_wish_items(self):
        wishitems = self.wishitem_set.all()
        total = sum([witem.quantity for witem in wishitems])
        return total

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    @property
    def get_total(self):
        total = self.product.price * self.quantity
        return total

class WishItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    wish = models.ForeignKey(Wish, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)

urls.py

from django.contrib.auth.views import PasswordChangeView
from . import views
from .forms import PasswordUpdateForm

urlpatterns = [
    path('', views.store, name="store"),
    path('cart/', views.cart, name="cart"),
    path('checkout/', views.checkout, name="checkout"),
    path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),
    path('registration/', views.registrationPage, name="registration"),
    path('profile/', views.profile, name="profile"),
    path('change_password/', PasswordChangeView.as_view(template_name='store/change_password.html', success_url='profile', form_class=PasswordUpdateForm ), name="change_password"),
    path('change_password/profile/', views.profile, name="profile"),

    path('filter_products/', views.filter_products, name="filter_products"),
    path('update_item/', views.updateItem, name="update_item"),
    path('update_wish_item/', views.updateWishItem, name="update_wish_item"),
    path('process_order/', views.processOrder, name="process_order"),
    path('wishlist/', views.wishlist, name="wishlist"),
    path('search/', views.search, name="search"),
    path('<int:id>', views.product_view, name="product_view"),
    path('search/<int:id>',views.product_view, name="product_view"),

]

utils.py

import json
from .models import *

def cookieCart(request):

    try:
        cart = json.loads(request.COOKIES['cart'])
    except:
        cart = {}
        print('CART:', cart)

    items = []
    order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
    cartItems = order['get_cart_items']

    for i in cart:
        try:
            cartItems += cart[i]['quantity']

            product = Product.objects.get(id=i)
            total = (product.price * cart[i]['quantity'])

            order['get_cart_total'] += total
            order['get_cart_items'] += cart[i]['quantity']

            item = {
                'id':product.id,
                'product':{
                    'id':product.id,
                    'name':product.name, 
                    'price':product.price, 
                        'imageURL':product.imageURL
                    }, 
                'quantity':cart[i]['quantity'],
                'digital':product.digital,
                'get_total':total,
                }
            items.append(item)

            if product.digital == False:
                order['shipping'] = True
        except:
            pass
            
    return {'cartItems':cartItems ,'order':order, 'items':items}

def cartData(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
        cartItems = order.get_cart_items
    else:
        cookieData = cookieCart(request)
        cartItems = cookieData['cartItems']
        order = cookieData['order']
        items = cookieData['items']

    return {'cartItems':cartItems ,'order':order, 'items':items}

    
def guestOrder(request, data):
    name = data['form']['name']
    email = data['form']['email']

    cookieData = cookieCart(request)
    items = cookieData['items']

    customer, created = Customer.objects.get_or_create(
            email=email,
            )
    customer.name = name
    customer.save()

    order = Order.objects.create(
        customer=customer,
        complete=False,
        )

    for item in items:
        product = Product.objects.get(id=item['id'])
        orderItem = OrderItem.objects.create(
            product=product,
            order=order,
            quantity=item['quantity'],
        )
    return customer, order


def cookieWishlist(request):

    try:
        wishlist = json.loads(request.COOKIES['wishlist'])
    except:
        wishlist = {}
        print('WISHLIST:', wishlist)

    witems = []
    wish = { 'get_wish_items': 0, 'shipping': False}
    wishItems = wish['get_wish_items']

    for i in wishlist:
        try:
            wishItems += wishlist[i]['quantity']

            product = Product.objects.get(id=i)

            wish['get_wish_items'] += wishlist[i]['quantity']

            witem = {
                'id': product.id,
                'product': {
                    'id': product.id,
                    'name': product.name,
                    'price': product.price,
                    'imageURL': product.imageURL
                },
                'quantity': wishlist[i]['quantity'],
                'status': product.status,

            }
            witems.append(witem)

        except:
            pass

    return {'wishItems': wishItems, 'wish': wish, 'witems': witems}


def wishData(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        wish, created = Wish.objects.get_or_create(customer=customer, complete=False)
        witems = wish.wishitem_set.all()
        wishItems = wish.get_wish_items
    else:
        cookieData = cookieWishlist(request)
        wishItems = cookieData['wishItems']
        wish = cookieData['wish']
        witems = cookieData['witems']

    return {'wishItems': wishItems, 'wish': wish, 'witems': witems}

and views.py

from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db.models import Max,Min
from django.template.loader import render_to_string
import json
import datetime
from .models import *
from .forms import CreateUserForm, UserUpdateForm
from .utils import cartData, guestOrder, wishData

def store(request):
    data = cartData(request)
    cartItems = data['cartItems']

    data1 = wishData(request)
    wishItems = data1['wishItems']

    products = Product.objects.all()
    minMaxPrice = Product.objects.aggregate(Min('price'), Max('price'))
    color = Color.objects.all()
    size = Size.objects.all()
    brand = Brand.objects.all()

    context = {'products':products, 'cartItems':cartItems, 'wishItems':wishItems,'color':color, 'size':size, 'brand':brand, 'minMaxPrice':minMaxPrice}
    return render(request, 'store/store.html', context)


def cart(request):

    data = cartData(request)
    cartItems = data['cartItems']

    data1 = wishData(request)
    wishItems = data1['wishItems']


    order = data['order']
    items = data['items']

    context = {'items': items, 'order': order, 'cartItems': cartItems, 'wishItems': wishItems}
    return render(request, 'store/cart.html', context)

def wishlist(request):
    data1 = wishData(request)
    wishItems = data1['wishItems']

    data = cartData(request)
    cartItems = data['cartItems']

    wish = data1['wish']
    witems = data1['witems']

    context = {'wishItems': wishItems,'cartItems': cartItems, 'witems': witems, 'wish': wish}
    return render(request, 'store/wishlist.html', context)

def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

    if action == 'add':
        orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
        orderItem.quantity = (orderItem.quantity - 1)

    orderItem.save()

    if orderItem.quantity <= 0:
        orderItem.delete()

    return JsonResponse('Item was added', safe=False)

def updateWishItem(request):
    data1 = json.loads(request.body)
    productId = data1['productId']
    action = data1['action']
    print('Action:', action)
    print('Product:', productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    wish, created = Wish.objects.get_or_create(customer=customer, complete=False)

    wishItem, created = WishItem.objects.get_or_create(wish=wish, product=product)

    if action == 'add':
        if wishItem.quantity != 1:
            wishItem.quantity = (wishItem.quantity + 1)
        else:
            wishItem.quantity = (wishItem.quantity + 0)
    elif action == 'remove':
        wishItem.quantity = (wishItem.quantity - 1)

    wishItem.save()

    if wishItem.quantity <= 0:
        wishItem.delete()

    return JsonResponse('Item was added', safe=False)

I want products to be added to the cart and not to the wishlist. Products added to the wishlist have the property of a cart. In the wishlist, I have a restriction on adding products, but there is no such restriction in the cart.
for example, I can only add one product of a certain type to a wishlist. But if I’m not logged in, I can add an infinite number to the wishlist (even by clicking on “add to cart”)

Trouble loading related entities in TypeORM

I am having an issue loading some data from my postgres DB with TypeORM. I have an entities for StaffTickets and Tags. They have a ManyToMany relationship connecting the two together. If I query my tickets table, looking for those with a specific tag, I get a response with the correct tickets back but they will only have 1 tag listed instead of many. On the ticket side the entity looks like:

    @ManyToMany(() => Tag, (tag) => tag.staffTickets)
    @JoinTable({
        name: 'staff_ticket_tags',
        joinColumn: {name: 'staff_ticket_id'},
        inverseJoinColumn: {name: 'tag_id'}
    })
    tags?: Tag[];

On the Tag side it looks like:

  @ManyToMany(() => Ticket, (ticket) => ticket.tags)
  tickets: Ticket[];

I have created some test tickets that have multiple tags. If I do a generic query, like the one below, I get a response with all of the tickets and a tag field that includes multiple tags.

tickets = await staffTicketRepo
                .createQueryBuilder('ticket')
                .leftJoinAndSelect('ticket.user', 'user')
                .leftJoinAndSelect('ticket.building', 'building')
                .leftJoinAndSelect('ticket.room', 'room')
                .leftJoinAndSelect('ticket.assignedTo', 'assignedTo')
                .leftJoinAndSelect('ticket.tags', 'tag')
                .getMany()

If I change the query, so that I am looking for tickets with a specific tag (see below). I get a response with the correct number of tickets but the tag field will only include the tag that I searched for. I would like it to include all of the tags associated with the ticket.

tickets = await staffTicketRepo
                .createQueryBuilder('ticket')
                .leftJoinAndSelect('ticket.user', 'user')
                .leftJoinAndSelect('ticket.building', 'building')
                .leftJoinAndSelect('ticket.room', 'room')
                .leftJoinAndSelect('ticket.assignedTo', 'assignedTo')
                .leftJoinAndSelect('ticket.tags', 'tag')
                .where('tag.label = :label', {label: req.query.type})
                .getMany()

I figured I can take these resulting ticket ids and query the tag repository to find all of the tags that have those ticket ids and then combine them after the fact

            const ticketIds = tickets.map(ticket => ticket.id);
            const relatedTags = await tagRepo
                .createQueryBuilder('tag')
                .leftJoinAndSelect('tag.staffTickets', 'staffTicket')
                .where('staffTicket.id IN (:...ticketIds)', { ticketIds })
                .getMany();

            for (const ticket of tickets) {
                ticket.tags = relatedTags.filter(tag => tag.staffTickets.some(st => st.id === ticket.id));
                }

But, that can’t be the best/efficient way to make this happen. What am I missing?

How Svelte is performance effective compared to react or angular

I have a question about svelte, if svelte is not adapting Virtual DOM or Shadow DOM mechanism, how is it generating high performance applications, because svelte is just a compiler, which generates the pure javascript build, is this is the only takeaway of svelte, converting to pure javascript code, will yeild you high performance applications?, then why react or angular using the Mechanism like Virtual DOM or Shadow DOM

I know this is not a coding question, but I wanted the answer, so only posted here, please do not delete or devote this post. I want to understand the internals

Thanks

WebRTC PeerConnection is not establishing in CHROME and EDGE

Below is the code for establishing peer connection from WEBRTC CLIENT and I am getting error Cannot create RTCPeerConnection object There is no problem with signaling server, socket.io or turn/stun servers.

Surprisingly it works MIRACLOUSLY in FIREFOX — but not in Chrome and Edge. Your kind help is greatly appreciated.

CODE

`
function createRTC(id, callback) {
    participants[id] = {}
    console.log(id)
    try {
        participants[id].pc = new RTCPeerConnection(pc_config);
    } catch (e) {
        console.log("Failed to create PeerConnection, exception: " + e.message);
       ** alert("Cannot create RTCPeerConnection object.");**
        return;
    }`

Expecting proper Webrtc connection between clients.

Unable to run API in Nodejs using mongodb

I am working with nodejs(expressjs),Right now i am trying to use “API” but i am getting following error

{"success":false,"error":{"ok":0,"code":8000,"codeName":"AtlasError"}}

Here is my “Controller file”(plan-ctrl.js)

export const getPlans = async (req, res) => {
    await Plan.find({}, (err, plans) => {
        if (err) {
            return res.status(400).json({ success: false, error: err })
        }
        if (!plans.length) {
            return res
                .status(404)
                .json({ success: false, error: `Plans not found` })
        }
        return res.status(200).json({ success: true, data: plans })
    }).clone().catch(err => console.log(err))
}

Here is my “model” (plan-model.js)

import mongoose from 'mongoose';
const Schema = mongoose.Schema

const Plan = new Schema(
    {
        name:  { type: String, required: true },
        price:  { type: Number, required: true },
        branches:  { type: Number, required: true },
        flows:  { type: Number, required: true },
        assignees:  { type: Number, required: true },
        gitignore:  { type: Boolean, required: true },
        priority:  { type: Boolean, required: true },
        multistore:  { type: Boolean, required: true },
    }
)
export default mongoose.model('plans', Plan)
Here is my data in database(mongodb/mongoose) in "claudmongo" ( connection established successfully)
_id : ObjectId(6390bfacbe1XXXXXXXXXXXX)
name:"Free"
price:"0"
branches:"2"
flows:2
assignees:null
gitignore:null
priority:null
multistore:false
color:"#969696"
...

How do i stop getting the “before all” hook error

I was given an instruction to define a function called introduction that defines a parameter, name, and returns the phrase: “Hi, my name is ${Name}.”

I keep getting this error after running “learn test” anyways and i have no idea how to get rid of it.

I tried this:

global.expect = require("expect");

const babel = require("babel-core");
const jsdom = require("jsdom");
const path = require("path");

function introduction(name) {
    return Hi, my name is {name};
}
console.log(introduction("Aki"));
console.log(introduction("Samip"));

And i got:

1) "before all" hook

  0 passing (569ms)
  1 failing

  1) "before all" hook:
     SyntaxError: /home/grgonyx/Development/code/phase-0-pac-3-function-parameters-lab/index.js: Unexpected token, expected ; (8:18)
     6 |
     7 | function introduction(name) {
  >  8 |     return Hi, my name is {name};
       |                   ^
     9 | }
    10 | console.log(introduction("Aki"));
    11 | console.log(introduction("Samip"));
      at Parser.pp$5.raise (node_modules/babylon/lib/index.js:4454:13)
      at Parser.pp.unexpected (node_modules/babylon/lib/index.js:1761:8)
      at Parser.pp.semicolon (node_modules/babylon/lib/index.js:1742:38)
      at Parser.pp$1.parseReturnStatement (node_modules/babylon/lib/index.js:2079:10)
      at Parser.pp$1.parseStatement (node_modules/babylon/lib/index.js:1848:19)

Download large file shared as presigned url in javascript

I have the following use case. We are using AWS presigned url which is SSE-C signed. We need to pass the required headers to use and download from the presigned url.
I have the below mentioned code which is working. The problem is that for large files, it is erroring out and there is no visal cue for the customer that the download is in progress or not.
Is there an easy way to download files for url(which need headers). if the headers wouldnt have been there, I could have simply done window.open to initiate the browser download.
Please suggest.

    function downloadFile() {
  const presignedUrl = 'myurl';


  //header
  const headers = {
    'x-amz-server-side-encryption-customer-algorithm': 'AES256',
    'x-amz-server-side-encryption-customer-key': 'abc',
    'x-amz-server-side-encryption-customer-key-MD5': 'xyz'
  };

  // fech with header
  fetch(presignedUrl, { headers })
    .then(response => {
      if (response.ok) {
        return response.blob();
      } else {
        throw new Error('Failed to download file');
      }
    })
    .then(blob => {
      // Save the file to local machine
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'file_download';
      document.body.appendChild(a);
      a.click();
      a.remove();
    })
    .catch(error => {
      console.error(error);
    });
}

JQuery contextMenu (by SWIS) – how to access textarea value from entry event/keyup function?

I’m trying to use input capabilities of jQuery contextMenu by SWIS, but documentation is very poor and I can’t find out how to obtain the value of text (here textarea) input value from within the events/keyup function.
I have hope that someone maybe know that library better or maybe authors didn’t describe it because it’s obvious for people who knows jQuery very well – so it’s not me.

<script src="includes/jquery.min.js"></script>
<link rel="stylesheet" href="js/contextmenu/jquery.contextMenu.css">
<link rel="stylesheet" href="js/contextmenu/foundation-icons/foundation-icons.css">
<script src="js/contextmenu/jquery.contextMenu.js"></script>
<script src="js/contextmenu/jquery.ui.position.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $.contextMenu({
        selector: '.jobs',
        zIndex: 10,
        build: function($triggerElement, e){
            return {
                items: {
                    quicknote: {
                        name: "Quick Note",
                        type: 'textarea', 
                        value: 'test', 
                        events: {
                            keyup: function(e) {
// Here I want to get edited value. 
// I've tried that, but didn't work: window.console && console.log($.contextMenu.inputs[0].$input.val()); 
                            }
                        }
                    },
                    "sep0": "---------",
                    copy: {
                        name: "Copy",
                        callback: function(itemKey, opt){ 
                            copyToClipboard(opt.$trigger.attr("name"));
                        }
                    },
                },
            };
        }
    });
});
</script>

As you see in the code – I’ve tried to use following path: $.contextMenu.inputs[0].$input.val() but it didn’t work. I was trying also e.data.$input.val(), this.$input.val() and many others, but it was blind search. Some found somewhere in the internet, but no success.

If someone could find the solution? I want the value of text area to be processed while editing. Basically every key press (while editing text area) should trigger some ajax function that will send value to the server. Ajax is not the issue, but the value, so if someone could help me with that I will be really grateful.
Thanks 🙂

Export method accessing outside variables [duplicate]

This is my prod.js file

arr = [1,2,3,4]

function sqr(num)

{    let u = sa + arr[1]
    return u ;
}

module.exports = sqr  // line A

This is my main.js file

let sqr = require("./prod")

function main()
{
 let  z = sqr(10) + 12

  return z
}

console.log(main())

Now , in line A I am only exporting my function sqr, and that function is imported in main.js. Now in main.js when i call that function , how is it able to access arr . I read that by exporting a function , a copy of the function is created in the other file in which we require it (main.js) then how am i able to access arr. In case of closure too it can access it if it would be in same file but not sqr function is in main.js in which there is not presence of arr , so how is it able to access it ?

React Modal not showing items after adding to context

I have created a React Context to manage a list of items, and I am using a modal to allow users to add new items. The problem is that when I add a new item and close the modal, the list of items is not updated automatically.

CartProvider

import React, { useState } from "react";

const CartContext = React.createContext({
  items: [],
  name_category: "",
  information_category: "",
  image_category: null,
  addItem: (item) => {},
  removeItem: (id) => {},
});

const CartProvider = (props) => {
  const [cartItems, setCartItems] = useState([]);
  const addItemHandler = (item) => {
    setCartItems((prevItems) => {
      return [...prevItems, item];
    });
  };

  const removeItemHandler = (id) => {
    setCartItems((prevItems) => {
      return prevItems.filter((item) => item.id !== id);
    });
  };

  const cartContext = {
    name_category: "",
    information_category: "",
    image_category: null,
    items: cartItems,
    addItem: addItemHandler,
    removeItem: removeItemHandler,
  };

  return (
    <CartContext.Provider value={cartContext}>
      {props.children}
    </CartContext.Provider>
  );
};

export { CartProvider, CartContext };

cartMoadl

import React, { useContext, useState } from "react";
import { GrCloudUpload, GrAddCircle } from "react-icons/gr";
import { IoIosAddCircleOutline } from "react-icons/io";
import Modal from "../../UI/Modal";
import { CartContext } from "@/store/CartProvider";

const Categories = (props) => {
  ///
  const [enteredName, setEnteredName] = useState("");
  const [enteredImageUrl, setEnteredImageUrl] = useState("");
  const [enteredDescription, setEnteredDescription] = useState("");
  const [items, setItems] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const cartContext = useContext(CartContext);
  //// start Open and Close Modal
  const showModalHandler = () => {
    setShowModal(true);
  };
  const closeModalHandler = () => {
    setShowModal(false);
  };

  ////end open and CLose Modal

  ///start content handler
  const nameInputChangeHandler = (event) => {
    setEnteredName(event.target.value);
  };

  const imageUrlInputChangeHandler = (event) => {
    setEnteredImageUrl(event.target.value);
  };
  const descriptionInputChangeHandler = (event) => {
    setEnteredDescription(event.target.value);
  };
  ////end content Handler

  ///start restform
  const restForm = () => {
    setEnteredName("");
    setEnteredImageUrl("");
    setEnteredDescription("");
  };
  ///end restForm

  ////start Add Handler

  const AddHandleClick = () => {
    const newItem = {
      id: Math.random().toString(),
      name: enteredName,
      imageUrl: enteredImageUrl,
      description: enteredDescription,
    };
    cartContext.addItem(newItem);
    setItems(cartContext.items);
    restForm();
    closeModalHandler();
    console.log("test");
  };

  ///end Add Handler

  return (
    <div className="grid grid-cols-3 gap-4 place-items-stretch h-56">

      {/* start show item  */}
      <div>
        {items.length > 0 &&
          items.map((item) => (
            <div key={item.id}>
              <h2>{item.name}</h2>
            </div>
          ))}
      </div>
       {/* end show item  */}
      <button
        onClick={showModalHandler}
        className="flex border-2 border-[#F8B162] rounded-lg h-[6rem] w-[10rem] justify-center items-center"
      >
        <IoIosAddCircleOutline
          style={{ color: "#F8B162" }}
          className="w-[5rem] h-[5rem] self-center"
        />
      </button>
            {/* start show modal */}
      {showModal && (
        <Modal onClose={closeModalHandler}>
          <form>
            <div className="flex flex-col items-center justify-center space-y-4">
              <input
                type="text"
                placeholder="Item name"
                value={enteredName}
                onChange={nameInputChangeHandler}
                className="w-full p-2 border border-gray-300 rounded-md"
              />
              <input
                type="text"
                placeholder="Image URL"
                value={enteredImageUrl}
                onChange={imageUrlInputChangeHandler}
                className="w-full p-2 border border-gray-300 rounded-md"
              />
              <textarea
                placeholder="Item description"
                value={enteredDescription}
                onChange={descriptionInputChangeHandler}
                className="w-full p-2 border border-gray-300 rounded-md"
              />
              <button
                onClick={AddHandleClick}
                className="px-4 py-2 font-medium text-white bg-blue-500 rounded-md"
              >
                Add to Cart
              </button>
            </div>
          </form>
        </Modal>
        // {/* end show modal */}
      )}
    </div>
  );
};

export default Categories;

Can anyone help me figure out why the list of items is not updated automatically when I add a new item and close the modal?

CSS reference not updating the referenced object

I am using a React app here.

.menu[data-active-index="0"] > .menu-background-pattern {
  background-position: 0% -25%;
}

This code is supposed to set the background position of the menu-background-pattern.
When i console.log(menu), i receive:

<div id="menu" data-active-index="0"></div>

so there is a match. yet, the css code is not executed on the menu-background-pattern. whats wrong here?