How to display api call response in Reactjs

I am new in Reactjs and i am working with nextjs, i tried to integrate “newsletter”,
I created a component for this which is working fine but i am unable to display “success” or “error”
message in screen/WebsitePage,i am getting “success” message in console but “success/error” message
not showing
Here is my code

import React, { useEffect, useState } from "react";

const Subscribe = () => {
 const [email, setEmail] = useState('');
 const [error, setError] = useState('');
 const [success, setSuccess] = useState('');

const subscribeMe = async (event) => {
            const emails = email;
            event.preventDefault();
            const res = await fetch('https://example.com/admin-panel/Api/subscribe?email='+emails);
            const { error, message } = await res.json();
            if (error) {
                    console.log(error);
                    setError(error);
            } else {
                    console.log(message);
                    setSuccess(message);
            }
};

And i put following code just below my form close,But nothing is showing in my screen,How can i do this ?

{success 
    ? 
        <span className="flex items-center text-sm font-bold text-green-700"> 
        {success}
    </span> 
    : 
<span className="flex items-center text-sm font-bold text-red-800">
{error} 
</span>

How can I replace or change object in data?

In my table it renders an array of users as rows in a table with <tr v-for="user in users" :key="user.id">

For the the column roles, instead of getting admin or user. The data is sending a 1 for admin and 2 for user. Is there a way that I can replace the array of that object? if its 1 = admin, 2 = user

data()
{
return {
  users: []
}


getUsers()
{
axios.get(url).then(response => { 
    this.users = response.data.report.users
})
}
<tbody>
                <tr v-for="user in users" :key="user.id">
                    <td>{{user.firstName}} {{user.lastName}}</td>
                    <td>{{user.email}}</td>
                    <td>{{user.role}}</td>
                </tr>
            </tbody>

table

I have an issue with long-long burger menu and sticky header, how to fix it?

I have a long mobile menu on my website, it works fine, but not with the sticky header script.
You can see it, if you delete or /comment/ the sticky header script
Codepen

I tried to copy all necessary styles and scripts, but without logo and icons, just imagine that burger svg is changing to ‘X’ when it’s opened. It’s only for mobiles, so I wrote max-width 485px, originally it was @media.

When submenu items are opened, I can’t scroll the window down.
The ‘overflow-hidden’ is only for x, for y it’s auto.
I tried to add

jQuery('header').removeClass('sticky');

there, inside

jQuery('.burger-toggle-item span.fa-burger').on('click', function() {
  jQuery(this).toggleClass('fa-burger fa-close');
  jQuery('.burger-menu-wrapper').slideToggle();
});

Tried to change position absolute to fixed.
How to make that menu and sticky header friendly to each other?

Opensearch nested multi_match query not working properly

I’m trying to run a multi_match nested query using javascript and opensearch. Here is what the query looks like:

const { body } = await client.search({
        index,
        body: {
            size: 25,
            query: {
                nested: {
                    path: "questions",
                    query: {
                        multi_match: {
                            query: searchText,
                            fields: ["question", "comments", "label", "user_answer"],
                        },
                    },
                },
            },
        },
    });

and here is my schema:

 questions: {
    type: "nested",
    properties: {
        question: { type: "text" },
        comments: { type: "text" },
        label: { type: "text" },
        user_answer: { type: "text" },
    },
}

I have other queries that are working properly and the actual search is just returning no hits, so I know the problem isn’t with opensearch and the setup. It seems that I just am doing the query wrong? Any help on this would be greatly appreciated, I can’t find examples on SO that work in my case and the documentation isn’t helping me much with this issue.

I Have a problem with my Google Authentication, displaying the error ‘pop-up closed by user’

I am trying to implement Google authentication in my web application, but I keep getting an error.
I generated my token on the Google Console Website, but when I try to sign in I get the error: “popup_closed_by_user”, when in the console I should have seen the credentials of the google account. Below is the code for the authentication:

 const googleSuccess=async (res)=>{
        console.log(res);
    };

    const googleFailure=(error)=>{
        console.log(error);
        console.log("Google Sign In was unsuccessful. Try Again Later.");
    };

<Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit}>
                {isSignup ? 'Sign Up' : 'Sign In'}
                 </Button>
                <GoogleLogin
                    clientId=""
                    render={(renderProps)=>(
                        <Button
                        className={classes.googleButton}
                        color="primary"
                        fullWidth
                        onClick={renderProps.onClick}
                        disabled={renderProps.disabled}
                        startIcon={<Icon/>}
                        variant="contained"
                        >
                            Google Sign In
                        </Button>
                    )}
                    onSuccess={googleSuccess}
                    onFailure={googleFailure}
                    cookiePolicy="single_host_origin"
                />

I have generated the token and put it in my code, but I deleted it for this post and I also cleared my cache and unchecked the “Block third-party cookies button” in my browser settings.
Could you help me?

Javascript String to Number Timer format +1 second to total time

I have a timer and a time. The time format is like the currentTime variable in my code. I want to get the currentTime time and add +1 to it every second keeping the same time format. Also I would like to subtract the currentTime + 1 – the total hours but keeping it real time with setInterval. Hope I am clear about my questions. Thanks.

Here is my code

let currentTime = 12:42:17;
let TotalHours = 30;
let seconds = 0;
let interval = null;
const timer = () => {
        seconds++;
        // Get hours
        let hours = Math.floor(seconds / 3600);
        // Get minutes
        let minutes = Math.floor((seconds - hours * 3600) / 60);
        // Get seconds
        let secs = Math.floor(seconds % 60);

        if (hours < 10) {
            hours = `0${hours}`;
        }
        if (minutes < 10) {
            minutes = `0${minutes}`;
        }
        if (secs < 10) {
            secs = `0${secs}`;
        }

        return `${hours}:${minutes}:${secs}`;
    };

startTimeButton.addEventListener("click", () => {
        pauseTimeButton.style.display = "flex";
        startTimeButton.style.display = "none";
        console.log("START TIME CLICKED");

        if (interval) {
            return;
        }

        interval = setInterval(timer, 1000);
    });

pauseTimeButton.addEventListener("click", () => {
        pauseTimeButton.style.display = "none";
        startTimeButton.style.display = "flex";
        console.log("PAUSE TIME CLICKED");
        clearInterval(interval);
        interval = null;

How to rotate an object around a distant pivot based on pivot rotation?

I’ve read the answer to the Three JS Pivot point question and it works okay.
But what I’m trying to accomplish involves also the object to rotate based on the pivot rotation.

Let’s say for instance that I have an object red that acts as a pivot for the little object blue. As soon as the red object moves or rotates, the blue object will move and rotate accordingly but keeping the distance between red and blue.

For simplicity in the following image we’re only in the situation in which the red object rotates only.

The signature of the function answered in the other question is the following:

function rotateAboutPoint(obj, point, axis, theta, pointIsWorld)

I don’t understand how do I get the axis and theta values starting from the red object rotation.

Or if that function doesn’t fit this case, I’m open for other solutions.

I know that if I add the blue object as a child of the red one everything will fall in place, but I need the two objects (red and blue) to be independent from each other.

To complicate things more I’m not rotating the red object directly, but I’m using ammo.js to apply force and torque on it as a dynamic body, but I guess that I can still know its rotation by using red.rotation

red pivot rotation

JS problem with the month of February in non-leap months

I am implementing a simple calendar, but i have a problem with all non-leap fever months.

If you click on next until February 2023, March is shown, if you advance until 2024 (which is a leap), everything works, how can I solve?

let nav = 0;

let test = () => {
  const dt = new Date();
  dt.setMonth(new Date().getMonth() + nav);
  const day = dt.getDate();
  const month = dt.getMonth();
  const year = dt.getFullYear();
  const monthName = `${dt.toLocaleDateString("en", { month: "long" })} ${year}`;
  
  console.log(1, month, year);
  
  document.getElementById('feedBack').innerHTML = 'Nav: ' + nav + ' - Day: ' + 1 + ' - Month: ' + month + ' ( <b>' + monthName + '</b> ) - Year: ' + year;
}

test();
#feedBack {margin-top:10px}
<button onclick="nav--;test()">Prev</button>
<button onclick="nav=0;test();">Current</button>
<button onclick="nav++;test();">Next</button>

<div id="feedBack"></div>

Django Ajax posting duplicate values to the view

Im trying to post the value of a html item(the id of the item) to the view so it can add the item to the cart, however it always posts the value of the last item printed by the django {% for %} even though the html source says the values are different

here is my html

 <div class="container">
    <div class="row row-cols-2 row-cols-md-3" data-masonry='{"percentPosition": true }'>
        {% for product in products %}
            <div class="col mb-4">
                <div class="card h-100">
                    {% if product.image %}
                        <img src="{{ product.image.url }}" class="card-img-top" alt="{{ product.description }}">
                    {% endif %}
                    <div class="card-body">
                        <h5 class="card-title">{{ product.name }}</h5>
                        <p class="card-text">{{ product.description|slice:":100" }}...</p>
                        <p class="card-text">${{ product.price }}</p>
                        <p>
                            <a class="btn btn-dark gap-2 mb-1" href="{{ product.get_absolute_url }}">View Item</a>
                            <button class="btn btn-outline-success" id="add-to-cart" value="{{ product.id }}">Add to Cart</button>
                        </p>
                        {% if product.in_stock == False %}
                        <p>
                            Item is currently out of stock
                        </p>
                        {% endif %}
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>
</div>

Here is the Ajax

$(document).on('click', '#add-to-cart', function(e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: '{% url "add_to_cart" %}',
        data: {
            productid: $('#add-to-cart').val(),
            csrfmiddlewaretoken: '{{ csrf_token }}',
            action: 'post'
        },
        success: function(json){

        },
        error: function(xhr, errmsg, err) {

        }
    });
})

Here is my view

def CartAddView(request):
cart = Cart(request)
if request.POST.get('action') == 'post':
    product_id = int(request.POST.get('productid'))
    product = get_object_or_404(Product, id=product_id)
    cart.add(product=product)
    response =JsonResponse({
        'price': product.price,
        'id': product.id, (here the id returned is always the id of the last element printed by the loop)
    })
    return response

i tried to make a product detail page and when i call the ajax it works perfectly

How to save dynamically added checkboxes’ styles after refreshing page?

To-do list. I have dynamic added checkboxes and styles for them in css. I wanna save checked checkboxes styles after refreshing the page using local storage. I’ve tried everything but nothing works. Any ideas? Thank you. (Also checkboxes are already in the local storage) Here’s full code https://github.com/cyber8nav/To-do-list

function addTask(nameOfTheNewTask) {
let task = {
    id: Date.now(),
    name: nameOfTheNewTask,
    completed: false
};

tasks.push(task);
textArea.value = "";
addTaskWindow.style.display = "none";
tasksWindow.style.display = "block";
if (tasks.length == 1) {
    amount.textContent = tasks.length + " " + "Task";
} else {
    amount.textContent = tasks.length + " " + "Tasks";
}
renderTask(tasks);
addToStorage(tasks);}
function renderTask(tasks) {
list.innerHTML = "";
tasks.forEach((item) => {
    const newTask = document.createElement("li");
    newTask.setAttribute("data-key", item.id);
    newTask.innerHTML = `
    <label class = "tasks__item">
        <input type = "checkbox" class = "checkbox" name = "task">
        <span>${item.name}</span>
    </label>
    <img class="delete" src="img/icons/delete.svg" alt="del" width="18px" height="20px">`;
    list.append(newTask);
});}
 // checkbox    
    &::before{
        content: '';
        display: inline-block;
        width: 1.2em;
        height: 1.2em;
        border-radius: 50%;
        border: 2px solid $darkgrey;
        position: absolute;
        left: 0;
        top: 0;
    }
}
// checked checkbox
input[type=checkbox] + span::after{
    content: '';
    opacity: 0;
    transition: opacity 0.6s ease;
}

input[type=checkbox]:checked + span::after{
    content: '✓';
    color: $blue;
    font-weight: 900;
    position: absolute;
    left: 0.225rem;
    top: -0.025rem;
    opacity: 1;
}
input[type=checkbox]:checked + span{
    color: $grey;
    text-decoration: line-through;
    animation: strike 1s linear;
    transition: color 0.6s ease-out;
}
input[type=checkbox]:checked + span::before {
    border: 2px solid $blue;
    transition: color 1s ease-out;
}

}

React.js and Mobx. ‘TypeError: cyclic object value’ if i try to find item in the mobx collection

My mobx class:

class ProductItems {
  products = [
    { id: 1, image: window.location.origin + '/images/tmp/01.png', price: '₴184.21' },
    { id: 2, image: '/images/tmp/02.png', price: '₴311.21' },
    { id: 3, image: '/images/tmp/03.png', price: '₴221.21' },
    { id: 4, image: '/images/tmp/04.png', price: '₴91.21' },
    { id: 5, image: '/images/tmp/05.png', price: '₴221.21' },
    { id: 6, image: '/images/tmp/06.png', price: '₴131.21' },
    { id: 7, image: '/images/tmp/07.png', price: '₴161.21' },
    { id: 8, image: '/images/tmp/08.png', price: '₴101.21' },
    { id: 9, image: '/images/tmp/09.png', price: '₴109.21' },
  ]

  constructor() {
    makeAutoObservable(this)
  }

  findById(id) {
    return this.products.filter(product => product.id === id)
  }
}

export default new ProductItems()

I try access to filtered product:

import './ProductDetail.css'
import { useParams } from 'react-router-dom'
import store from '../../store/products-store'
import { observer } from 'mobx-react-lite'
import { useEffect, useState } from 'react'

const ProductDetail = () => {
  const { id } = useParams()
  const [product, setProduct] = useState({})
  useEffect(() => {
    setProduct(store.findById(+id))
    // setProduct(store.products.find(product => product.id == id))
  }, [id])
  const { price, image } = product
  return (
    <section className="product-detail">
      <div>
        Product Page: {id}
      </div>
      <div>Price: {price}</div>
      <div>Image: {image}</div>
    </section>
  )
}

export default observer(ProductDetail)

It works correctly and result expectable, but in the console i’m having error messages all the time:

TypeError: cyclic object value    react_devtools_backend.js:4026:25
    parseData _product.css:8
    i _product.css:10
    i _product.css:10
    _ _product.css:10
    _ _product.css:10
    l _product.css:10
    emit 1:334
    emit 1:334
    attachRenderer react_devtools_backend.js:16201
    initBackend react_devtools_backend.js:16213
    initBackend react_devtools_backend.js:16212
    setup react_devtools_backend.js:13122
    welcome react_devtools_backend.js:13068
    EventListener.handleEvent* react_devtools_backend.js:13071
    __webpack_require__ react_devtools_backend.js:20
    <anonymous> react_devtools_backend.js:84
    <anonymous> react_devtools_backend.js:87

I have no idea why it happens so i can’t ignore this error until reason realized.
I hope that someone came across something similar and could share explanations.
Thanks.

P.S.

more details

sergii:~$ node -v
v16.5.0
sergii:~$ npm -v
7.19.1

package.json

        "mobx": "^6.6.1",
        "mobx-react-lite": "^3.4.0",
        "react": "^18.1.0",
        "react-dom": "^18.1.0",