JS Promise function call that returns object

I have a async fetch function that waits 2 seconds and returns a object:

async function fetch() {
    var object;
    await setTimeout(() => { object = { name: 'User', data: 'API Data' } }, 2000);
    return object;
}

I want to display the object when the initialization is completely done (after 2 seconds)

fetch().then((val) => {
    console.log("DONE!"); 
    console.log(val.name);
}).catch((err) => {
    console.log("ERROR!");
    console.log(err);
});

The code prints both DONE and ERROR Cannot read properties of undefined (reading 'name')

I have tried with Promise, no luck

let promise = new Promise((resolve, reject) => {
    let request = fetch();
    if (request !== undefined)
        resolve(request);
    else
    reject(request);

}).then((val) => {
    console.log(val);
});

How can I properly check that fetch() has returned a value before printing without changing the inside of the function. I can delete the async and await in it but I am unable to edit it (I.E. adding a Promise inside)

Mantine date picker throws an objects are not valid as a react child error

I’m trying to use mantine Date in NextJS. When a user clicks on the date, that date suppose to display the date in the html text heading. For example, if a user picks the date jan 1st 2023, the text is supposed to look like Date: Sun Jan 01 2023... I’m testing it out using a console.log and it works. However, when I try to use it in the text heading this error gets thrown: Error: Objects are not valid as a React child (found: [object Date]). If you meant to render a collection of children, use an array instead.

I tried adding a map to it that didn’t work. Then I tried using const date = [...calendarVal] but it said TypeError: calendarVal is not iterable

import { useState, useEffect } from 'react';
import { Modal, Button, Group } from '@mantine/core';
import { Calendar, RangeCalendar } from '@mantine/dates';
import React  from 'react';

export default function Demo() {
  const [opened, setOpened] = useState(false);
  const [calendarVal, setCalendarVal] = useState(Date());
  const [hydrated, setHydrated] = React.useState(false);

  React.useEffect(() => {
    setHydrated(true);
  }, []);

  useEffect(() => {
    console.log(calendarVal)
  })

  if (!hydrated) {
    // Returns null on first render, so the client and server match
    return null;
  }
  
  return (
    <>
      <Modal
        opened={opened}
        onClose={() => setOpened(false)}
        title="Introduce yourself!"
      >
        {/* Modal content */}
      </Modal>

      <Group position="center">
        <Button onClick={() => setOpened(true)}>Open Modal</Button>
        
      </Group>
      
      <p>Date: {calendarVal}</p>
      <Group position='center'>
        <Calendar onChange={setCalendarVal} value={calendarVal}  />
      </Group>

    </>
  );
}

How can i fix this error ERROR TypeError: undefined is not an object (evaluating ‘userData.username’)

Can anyone help me to fix this error? the error says ERROR TypeError: undefined is not an object (evaluating ‘userData.username’) when I test this API in postman it gives results also when I am logging the username and profile pic value then in the backend its logs but when in frontend it’s giving me error What is the solution of this error and how can I display the username and profile coming from backend? and also one thing I get the user city name by expo location I also have a city in my user schema which is a string and when a user agrees on the permission of location then the city gets saved in the database

Backend:

router.get("/user", async (req, res) => {
    try {
      const city = req.body.city;
  
      console.log(city);
  
      const count = await User.countDocuments({ city: city });
      if (count === 0) {
        return res.status(404).json({ error: "No users found with that city" });
      }
  
      const randomUser = await User.aggregate([
        {
          $match: {
            city: city,
          },
        },
        {
          $sample: {
            size: 1,
          },
        },
        {
          $project: {
            username: 1,
            profilepic: 1, 
          },
        },
      ]);

      console.log(randomUser[0].username)
      console.log(randomUser[0].profilepic)
  
      res.json(randomUser);
    } catch (err) {
      console.log(err);
      res.status(500).json({ error: err });
    }
  });

Frontend:

import { StyleSheet, Text, View, Image } from 'react-native'
import React, { useState, useEffect } from 'react'

const SearchUserPage = () => {
  const [userData, setUserData] = useState();

  useEffect(() => {
    async function fetchUser() {
      try {
        const response = await fetch('http://10.0.2.2:3000/user');
        setUserData(response.data);
      } catch (error) {
        console.error(error);
      }
    }

    fetchUser();
  }, []);
  
  return (
    <View style={styles.container}>
      <View style={styles.userSection}>
        <View style={styles.imageContainer}>
          <Image
            style={styles.image}
            source={{ uri: userData.profilepic }}
            resizeMode="contain"
            overflow="hidden"
          />
        </View>
        <Text style={styles.text}>{userData.username}</Text>
      </View>
    </View>
  )
}

export default SearchUserPage

How to make loop not to continue until an event happens?

I am writing a function of a game:

function Game(){
    while(true){
        var level = 1;
        $("#level-title").text("Level " + level);
        var colorsOrder = [];
        var randColor = GenerateRandomSquareColor();
        colorsOrder.push(randColor);
        ButtonClickResponse(randColor);

        for(var i = 0; i < level; i++){
            var color;
            $(".btn").on("click", function(event) {
                ButtonClickResponse(this.id);
                color = this.id;
            });
            if(colorsOrder[i] != color){
                GameOver();
                return;
            }
        }
        level++;
    }
    
}

the “if statement” in the loop of function runs immediately when loop is started and doesnt wait for an above event to finish.

I searched for solving with “async await” and “promise” in google and stackoverflow, but didn’t really understand how it worked so couldn’t implemet it in my code.

What is the expected behavior when an error occurs in a JavaScript catch block? [closed]

While testing some JavaScript try/catch code that wasn’t working as expected, I finally noticed that I was attempting to use an undeclared variable in the catch block.

What made this so tricky to find, was that the browser did not indicate any errors or warnings, related to the undeclared variable or otherwise, and seemed to simply exit the catch block at the point of the error and move on.

Is this the expected behavior when an error occurs in a catch block?

js object sending through ajax

i have spent two days trying to get resolved the issue but cant get it done.
So i am sending session stored in browser through jQuery ajax to php function so that to save the data to wordpress db.

in session Storage data is stored like this –

 [{"name":"том","price":259,"count":1},{"name":"жак","price":299,"count":1}]     

so this is how i try to make it done but it doesn’t work

var sessionStorage = JSON.stringify(sessionStorage.getItem('shoppingCart'));


       $.ajax({
            url: "https://mywebsite.com/wp-admin/admin-ajax.php",
            method: "POST",
            data: 'globalvar='+sessionStorage+'&action=myfunction',
             dataType: "json"  
        }).done(function (response) {


});
});

the php function is:

if (!function_exists('myfunction')) {

function myfunction() {
    

     
  $object = $_POST['globalvar'];
     
     $decoded_object = json_decode($object);

       //wordpress update db                 
      update_post_meta('42393', 'menu_items_list',  $menu_make_arr);
        
 }

     
             add_action('wp_ajax_myfunction', 'myfunction');
            add_action('wp_ajax_nopriv_myfunction',  'myfunction');
}

i get null in db like this

wordpress database image

Django – stop logout with javascript pop-up confirm box

In my django site I have a logout button that redirects to the view logout. When the button is clicked it instantly logs the user out, but I would like a JS pop-up confirm box to appear then the logout button is clicked.

When the user clicks ‘Ok’ OR ‘Cancel’ it logs the user out. How can i prevent the logout view being called when the user clicks ‘Cancel’?

views.py

def logout(request):
    if "user_info" in request.session:
        del request.session["user_info"]
    #redirect to login so the user can log back in
    return redirect("login")

script.js

function logout_popup() {
    if (confirm("Are you sure?")) {
        window.location.reload()
    }
}

base.html

<li onclick="logout_popup()" id="logout-tab"><a href="{% url 'logout' %}">Logout</a></li>

Array groupping with condition in javascript

So i have an array of response from BE with structure like this:

const answer= [
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "34",
    "Shift Running": "3",
    "SKU Number": "310902",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "34",
    "Shift Running": "2",
    "SKU Number": "310902",
    "RPH Input": "Revisi"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "36",
    "Shift Running": "3",
    "SKU Number": "300360",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "36",
    "Shift Running": "3",
    "SKU Number": "310907",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "37",
    "Shift Running": "3",
    "SKU Number": "310908",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "11",
    "Line": "43",
    "Shift Running": "1",
    "SKU Number": "310101",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-06",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "11",
    "Line": "43",
    "Shift Running": "2",
    "SKU Number": "321294",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-06",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "11",
    "Line": "44",
    "Shift Running": "3",
    "SKU Number": "300079",
    "RPH Input": "Planned (H-1)"
  }
]

i try to grouped it into date with condition if the “Tanggal”,”Plant”,”Gedung/Zona”,”sektor”,Line,Shift Running, and SKU number is the same but the RPH input has value “Revisi”, it will only group the value from RPH input that has value revisi instead of the Planned (H-1), with expected array to be like this, the value of the date is the accumulated value from Shift Running (here is the expected array):

const tranfrdata=[{ "2023-01-05": 12,
  "2023-01-06": 5 }]

it possible to just group it based on the logic i mention above, is that possible to do that? or any help on this?

which windows to use for software development

I’ve been working on web and mobile development using javascript for a while (react native and nodejs) I’m using windows 11 right now, they say windows 10 is more performance, do you think I will get more performance which windows version I use?

My laptop lenovo ideapad 3 with ryzen 3 3250U and 8 ram

How do I move the videojs control bar out of the video area or duplicate a videojs control bar?

I used a canvas element to pixelate a video by covering it on the video. But the canvas element will cover the control bar. So is there a way to move the control bar out of the video area or hide the original one and duplicate a new videojs control bar?

control bar in the video area](https://i.stack.imgur.com/ZykMJ.png)

By the way, is this the best practice to pixelate a video in front end?

Array groupping with condition javascript [closed]

So i have an array of response from BE with structure like this:

const answer= [
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "34",
    "Shift Running": "3",
    "SKU Number": "310902",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "34",
    "Shift Running": "2",
    "SKU Number": "310902",
    "RPH Input": "Revisi"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "36",
    "Shift Running": "3",
    "SKU Number": "300360",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "36",
    "Shift Running": "3",
    "SKU Number": "310907",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "9",
    "Line": "37",
    "Shift Running": "3",
    "SKU Number": "310908",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-05",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "11",
    "Line": "43",
    "Shift Running": "1",
    "SKU Number": "310101",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-06",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "11",
    "Line": "43",
    "Shift Running": "2",
    "SKU Number": "321294",
    "RPH Input": "Planned (H-1)"
  },
  {
    "Tanggal": "2023-01-06",
    "Plant": "Ranc",
    "Gedung / Zona": "Zona 2",
    "Sektor": "11",
    "Line": "44",
    "Shift Running": "3",
    "SKU Number": "300079",
    "RPH Input": "Planned (H-1)"
  }
]

i try to grouped it into date with condition if the “Tanggal”,”Plant”,”Gedung/Zona”,”sektor”,Line,Shift Running, and SKU number is the same but the RPH input has value “Revisi”, it will only group the value from RPH input that has value revisi instead of the Planned (H-1), with expected array to be like this, the value of the date is the accumulated value from Shift Running:

const tranfrdata=[{ "2023-01-05": 12,
  "2023-01-06": 5 }]

it possible for me to just group it based on date, but for the logic i mention above, is that possible to do that? or any help on this?

I want to prevent Direct IP is not allowed

I’m so sorry, I want this feature
I don’t have info on it to give you an example
But there is another site that uses it
From here: http://135.125.251.122
If you enter through IP, the site says Direct IP is not allowed
Then it automatically brings me to the domain

All I found is this code

<script language="JavaScript">window.alert("Direct IP is not allowed")</script><script language="JavaScript">window.open("https://example.com", "_self")</script>

jsONDecodeError. AJAX + Django. Comment system

I’m trying to implement a comment system in Django. The problem is that I can add a comment to the very first post and AJAX will work, that is, the comment will be published without reloading. But if I try to leave a comment on the following posts, I stumble upon an error: jsONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0).

In data = json.loads(request.body), there is a post_id and a body, but only if you leave a comment on the first post. To the rest of the request.body is just an empty string

models.py

from django.utils import timezone
from django.db import models
from django.contrib.auth.models import User


class Post(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='posts')
    title = models.CharField(max_length=30)
    body = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=timezone.now())
    
    def __str__(self) -> str:
        return self.title


class Comment(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='comments')
    body = models.CharField(max_length=255)
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, related_name='comments', blank=True)
    created_at = models.DateTimeField(auto_now_add=timezone.now())

    def __str__(self) -> str:
        return self.body

views.py

from django.utils.formats import date_format
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from .models import *
from django.shortcuts import render
import json


def post_detail(request):
    quotes = Post.objects.all()

    context = {
        'quotes': quotes,
    }

    return render(request, 'app_one/post_detail.html', context)


def comment_create(request):
    data = json.loads(request.body)
    post_id = data['post_id']
    comment_body = data['body']

    user = User.objects.get(date_joined='2023-01-08 12:00:29.481762')

    post = get_object_or_404(Post, id=post_id)
    comment = Comment.objects.create(
        user=user,
        body=comment_body,
        post=post
    )

    created_at = date_format(
        comment.created_at, format='M. d, Y, h:m a', use_l10n=True)

    return JsonResponse({
        'user': comment.user.username,
        'body': comment.body,
        'created_at': created_at
    })

post_detail.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
    <title>Document</title>
</head>

<body>
    {% for post in quotes %}

    <h1>{{post.title}}</h1>
    <h4>{{post.created_at}}</h4>
    <p>{{post.body}}</p>

    <hr>

    <div id="comment-div">
        <form action="{% url 'love:comment-create' %}" id="comment-form">
            <input type="hidden" id="post-id" value="{{post.id}}">
            <textarea id="comment-body" maxlength="255" rows="4" cols="50"></textarea>
            <br>
            <button type="submit" id="submit-comment">Comment</button>
        </form>
        <hr>
    </div>

    <div id="comment-list">
        <h2> Comments </h2>
        {% if post.comments.all %}
        {% for comment in post.comments.all %}
        <p>At {{comment.created_at|date:"M. d, Y, h:m a"}} {{comment.user}} commented:</p>
        <p>{{comment.body}}</p>
        {% endfor %}
        {% endif %}
    </div>
    {% endfor %}


    <script>
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        $('#submit-comment').click(function (e) {
            e.preventDefault();
            var url = $('#comment-form').attr("action");
            var post_id = $('#post-id').attr("value");
            var body = $('#comment-body').val();
            const csrftoken = getCookie('csrftoken');

            console.log(post_id)
            console.log(body)
            $.ajax({
                method: "POST",
                url: url,
                headers: { 'X-CsrfToken': csrftoken },
                data: JSON.stringify({ post_id: post_id, body: body }),
                success: function (comment) {
                    // $('#comment-div').prop("hidden", true);
                    $('#comment-body').val('');
                    $('#comment-list').append(
                        `<p>At ${comment.created_at} ${comment.user} commented:</p> 
                        <p>${comment.body}</p>`
                    );
                }
            });
        });
    </script>
</body>

</html>

What could be the problem?

And another small problem: when I try to enter a user into the console, an Anonymous User comes out. And when I check for user authentication, the verification does not pass, although I entered the admin panel

What could be the problem?

And another small problem: when I try to enter a user into the console, an Anonymous User comes out. And when I check for user authentication, the verification does not pass, although I entered the admin panel

How can I reassign XHR without reloading the page in JavaScript?

This is a PHP Bootstrap CODE I try to dynamically change bootstrap modal body content that can I can easily add or edit product category . Then I submit the entered or changed data to save into database by submitting the form through Ajax .
I use pure JavaScript Ajax request to done this job for me.
For the first time when I click into Create Product Category Everything work fine. But when the first time content add then I try to add anther product the second product will automatically add two times it will increase for the forth time and so on .
I know the problem . But I can’t solve it.
how can I reassign or how can I Completely clean Ajax after the task done then after clicking to create new product category I will renew Ajax ?
this is my JavaScript Ajax code :

// get add category 
document.getElementById('add_category').addEventListener('click', () => {

    var xhr = new XMLHttpRequest();

    xhr.open("GET", 'add.php', true);
    console.log("add_category")
    xhr.onload = function() {
        if (this.status == 200) {
            document.getElementById('exampleModalLabel').innerHTML = 'Create Product Category';
            document.getElementById('modal-body').innerHTML = this.response;
            // console.log(this.response)
            dynamicChangePicture()

            // on change category_name
            onChangeCategoryName('category_name');

            // add new Category
            document.getElementById('save_btn').addEventListener('click', (e) => {
                e.preventDefault();
                console.log('save_btn')
                var xhr = new XMLHttpRequest();
                xhr.open('POST', `../includes/functions.php`, true)
                xhr.onload = function() {
                    if (xhr.status == 200) {
                        console.log(xhr.response)

                        if (xhr.response == 'category name add successfully! ') {

                            document.getElementById('close_modal_btn').click();
                            showMessage(xhr.response, 'Add')
                            console.log(xhr.responseText)
                            // document.getElementById('logo_box').innerHTML = `<span class='text-success'>${xhr.response}</span>`;
                        } else {
                            showMessage(xhr.response, 'Remove')
                            document.getElementById('logo_box').innerHTML = `<span class='text-danger'>${xhr.response}</span>`;
                        }


                        setTimeout(() => {
                            document.getElementById('table-body').innerHTML = '';
                            defaultLoad();
                            console.log("data Loaded")
                        }, 5000)
                    }
                }
                const formData = new FormData(document.getElementById('add_category_form'))
                xhr.send(formData);
            })
        }
    }
    xhr.send();
})

even I Change inside xhr variable with the a deferent one it will still have the same problem.