Animation not happening In React Component

I am trying to achieve animation in a react app. The styles are getting imported from .js file (CSS in JS?). And those styles are getting applied except for the animation. The animation isn’t working.

Styles.js containing styles is as below:

import { keyframes } from '@emotion/react';

const bounceAnimation = keyframes`
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(20px);
  }
`;
const classes = {
  loadingContainer: {
    fontSize: '84px',
    fontWeight: 800,
    textAlign: 'center',
  },
  loadingSpan: {
    display: 'inline-block',
    animation: `${bounceAnimation} 0.7s infinite`,
    color: 'red',
    margin: '0 -.05em',
  },
};

export default classes;

The React Component is as below:

import React from 'react';
import styles from './styles';

const Loader = () => {
  return (
    <div style={styles.loadingContainer}>
      <span style={styles.loadingSpan}>loading</span>
    </div>
  );
};

export default Loader;

Sort a nested list of items via drag and drop

Nested Sort is a JavaScript library which helps you to sort a nested list of items via drag and drop. But I want to make this in vanilla javascript . How to I make this?

I try it in drag and drop system using index.I use html5 dragable attribute, I want to need it in row js

How to change the icon color when button is active?

How to change the colors of icons when the active state of the button is changed? I’m using SVG icons since they are convenient. How can I modify the SideBarButton component to conditionally apply styles to the icon based on the active state. How can I achieve this ? Here are the SideBarButton and SideBar component codes (briefly)

const SideNavbar = ({ onSideNavBarClick }) => {
  const [activeButton, setActiveButton] = useState("Dashboard");

  const handleClick = (page) => {
    setActiveButton(page);
    onSideNavBarClick(page);
  };

  return (
    <SidebarWrapper>
      <SidebarBody>
        <UnorderedList>
          {makeButtons.map((btn, i) => (
            <SideBarButton
              key={i}
              onClick={() => handleClick(btn.title)}
              icon={btn.icon}
              title={btn.title}
              isActive={btn.title === activeButton}
            />
          ))}
        </UnorderedList>
      </SidebarBody>
    </SidebarWrapper>
  );
};

const makeButtons = [
  { icon: <img src={dashboard} alt="dashboard" />, title: "Dashboard" },
  { icon: <img src={patient} alt="patient" />, title: "Patients" },
  { icon: <img src={visits} alt="visits" />, title: "Appointments" },
  { icon: <img src={appointments} alt="appointments" />, title: "Visits" },
];
const SideBarButton = ({ onClick, icon, title, isActive }) => {
  return (
    <li>
      <ButtonSidebar onClick={onClick} className={isActive ? "active" : ""}>
        <Icon>{icon}</Icon>
        {title}
      </ButtonSidebar>
    </li>
  );
};

#react #js #frontend

How Can I Connect Using A WebRTC-Offer With PeerJS

I want to be able to connect using PeerJS but with a WebRTC connection offer. In the docs it is like: var conn = peer.connect('dest-peer-id');
https://peerjs.com/docs/#peerconnect

I see that the peer object exposes the underlying RTCPeerConnection. Is it possible for me to connect peers this way? i am hoping for something like:

// on computer-1
let offer = await peer.RTCPeerConnection.createOffer()


// on computer-2
let conn = peer.connect({ offer });
// or
let conn = peer.RTCPeerConnection.connect({ offer });

Is there a way i can use the undelying RTCPeerConnection to connect to a peer. Im hoping this could be a way to connect without requiring a peer-broker.

Processing input csv using JS on client

I have a form view where the user can upload a csv file. 

source_file = fields.Binary(string='CSV Input', attachment=True)

<field name="source_file"/>

I want to have a button ‘Validate CSV’ that will run a js function to validate the csv for any non-printable characters and show any rows that contain invalid characters in the view

I am new to odoo development so I am not able to bind the js function to the button and access the file in the js function

I can figure out the validation logic but I need help with the js file syntax such that it will be bound to the button and show the result in the view

Thanks a lot

I tried writing the js function in static/src/js folder, the file loads when the page loads but the button is disabled by default. Looks like it cant find the function or something. I am also doubtful about how the js will fetch the file from the DOM or field

I can’t display the items from an array in an ejs view

Attached is a node.js route for displaying product data for the product ids that a user enters in an html form. In this route, I have the array ‘prod_id_arr’ with product ids. For each prod_id in this array, I select the mysql product database row and add it to another array ‘data’. I then use the ‘data’ array to display the product data in “prod_multi_upd_pg” view at the end. When I console.log the data array, I see it is populated. However, it fails in the “prod_multi_upd_pg” view with the message “Cannot read properties of undefined (reading ‘prod_id’)”. Interesting thing is that when I assign a single occurrence of the data array (i.e. data[0] or data[1]) to another array adata and pass the adata array to the ejs view, it works for that single item. I don’t understand how js logic works, it is very confusing. What do I have to do to display all items? Any help will be appreciated.

// Route to display current data for multiple product updates. 
app.get('/prod_multi_upd_pg', async (req, res) => {
    let prod_id_arr = req.query.prod_id_arr.split(','); 
    let data = []; 
    const fetchData = async (prod_id, index) => {
        return new Promise((resolve, reject) => {
            con.query('SELECT * FROM product WHERE prod_id = ?', [prod_id], function(err, row) {
                if (err) {
                    reject(err);
                } else {
                    resolve(row.length === 0 ? null : row);
                    console.log("row: ", row)
                }   
            });
        }); 
    };  
    try {
        const dataPromises = prod_id_arr.map((prod_id, index) => fetchData(prod_id)); 
        const data = await Promise.all(dataPromises);
        res.render("prod_multi_upd_pg", {data}); --> this doesn't work. 
                 But when I replace this line with the following 3 
                 lines, it works for that single item.
                                    let adata = [];
                                    adata = data[0];
                                    res.render("prod_multi_upd_pg", { adata });
            
    } catch (error) {
        alert("Ürün kodu bulunamadı, lütfen geçerli bir ürün kodu girin.");
        res.status(500).send("Internal Server Error");
    }
})
<tbody>
              <% if(data.length){for(let i = 0; i< data.length; i++) {%>
                  <tr>
                    <td><%=data[i].prod_id%></td>
                    <td><%=data[i].saleprice%></td>
                    <td><%=data[i].stock_quantity%></td>
                    <td><%=data[i].max_order_qty%></td>
                    <td><%=data[i].time_to_cargo%></td>
                  </tr> 
              <%} }else{ %> 

Calculating the difference of two reduced arrays [closed]

I am trying to make a budget tracker. I have been researching how to go about doing it and found some code here that I studied, used and modified a bit in my project.

I have been using array .reduce and .map to get the final sum of all the inputs but struggling with how to use final numbers to then subtract to each other and get a ‘final balance’.

I tried to create a let variable to assign to the final sums but every time, and then subtracted them from each other however, it either returns as NaN or 0.

let totalIncome = incomeTotal.value;
let totalExpense = total.value;


//total income
income.forEach(x =>
  addEventListener("input", (e) => {
  
    incomeTotal.value =
      Array.from(income)
      .map((x) => x.value)
      .reduce((accumulator, currentValue) => +accumulator + +currentValue, 0);
  
//expense
    total.value =
      Array.from(input)
      .map((x) => x.value)
      .reduce((accumulator, currentValue) => +accumulator + +currentValue, 0); 
  
 
//final

  finalValue.value = (+totalIncome - +totalExpense);  
}));

Why does this debounce return undefined?

I was trying to implement debounce but it did not work as expected, I could not understand why, the debounced function was not returning anything. it was returning undefined

const debounce = (mainFunction, delay) => {
  let timer;

  return function (...args) {
    clearTimeout(timer);

    timer = setTimeout(() => {
      return mainFunction(...args);
    }, delay);
  };
};

function searchData() {
  console.log("searchData executed");
  return "hello";
}

const debouncedSearchData = debounce(searchData, 3000);

const testData = debouncedSearchData();
console.log(testData);

I couldn’t publish the HTML code containing the Javascript in my WordPress site

I have been trying to add HTML code containing Javascript from an Affiliate platform to my blog site.

I copy pasted the code from Klook/Headout site(affiliate platform) and pasted in the HTML code blocks. But after pasting the code, the wordpress editor shows the preview of the code within the block editor but not on the actual preview page. When I hit publish it throws errors such as – The response is not a valid JSON reponse, Server error(403 error), the firewall like cloudfare etc., in your site is’t allowing to publish. I tried again by removing the script tag, by this way it allows me to publish the code. Kindly help to solve this issue. Fyi: I am not a pro in coding. Attaching the screenshot of the issue showing in the browser console. View the screenshot here

<script type="text/javascript">
  (function (d, sc, u) {
    var s = d.createElement(sc),
      p = d.getElementsByTagName(sc)[0];
    s.type = "text/javascript";
    s.async = true;
    s.src = u;
    p.parentNode.insertBefore(s, p);
  })(
    document,
    "script",
    "https://affiliate.klook.com/widget/fetch-iframe-init.js"
  );
</script> ````


  [1]: https://i.stack.imgur.com/zm3Pi.jpg

my javascript bar chart doesn’t come up on my index.html page

Heyy, I’ve been working on my web app project and I needed to do graph so I tried it separately in another file and it works so well but when I paste in the index.html it doesn’t I don’t know why

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
</script>
<canvas height="400" id="barChart" width="400"></canvas>
<script>
var data = {
    labels: ["AIs", "CS", "DSA", "ISM", "SE"],
        datasets: [{
            label: "2020 Intake",
            data: [0.69, 0.7, 0.68, 0.71, 0.74],
            backgroundColor: ["#fcedf5", "#fad7e9", "#fcbdde", "#ffb0d9", "#fc9acd"],
            borderColor: "#fff",
             borderWidth: 1
        },{
            label: "2021 Intake",
            data: [0.78, 0.67, 0.76, 0.71, 0.74],
            backgroundColor: ["#fcedf5", "#fad7e9", "#fcbdde", "#ffb0d9", "#fc9acd"],
            borderColor: "#fff",
            borderWidth: 1
        }]
    };
var ctx = document.getElementById("barChart").getContext("2d");
var myNewChart = new Chart(ctx, {
    type: 'bar',
    data: data,
        options: {
            indexAxis: 'y',
            scales: {
            x: {
                min: 0,
                max: 1,
                ticks: {
                callback: function(value) {
                return (value * 100) + "%";
                }}}}}
        });
</script>

Could you help me please

Queueing system using Python Flask

So I’ve been trying to make a queueing system for an omegle clone.
Here, there is an empty “queue” dict. Whenever there is post request, i.e someone clicked on the CHAT button, one of 2 things can happen.

(1) If the queue dictionary is empty, create a random code, create a new item in queue, and save the info via sessions. After that, display a waiting screen (waiting.html). And check in a While loop if there are 2 members, in that case, redirect to /chat.

(2) If the queue dictionary is NOT empty, the code will be the first item in the dictionary’s key, which is a random 4 digit code, append your name in the member’s list of the item, and save all the stuff via sessions.
After that, if the number of members (len(members_list)) is 2, then redirect to /chat

Here’s the code:

#on submitting info / on post request / clicking on the chat button
        if len(queue) == 0:
            code = "".join(random.choices(ascii_uppercase, k=4))
            queue[code] = {"members" : [name]}

            session["name"] = name
            session["favColor"] = favColor
            session["code"] = code

            while len(queue[code]["members"]) == 1:
                return render_template("waiting.html")
            else:
                return redirect(url_for("chat"))
        
        else: 
            code = next(iter(queue))
            queue[code]["members"].append(name)

            session["name"] = name
            session["favColor"] = favColor
            session["code"] = code

            if len(queue[code]["members"]) == 2:
                return redirect(url_for("chat"))

First to check if the number of members are 2, I used an IF statement in the if len(queue) == 0: block.
Later when it didn’t work, i used the while loop. ITS STILL NOT WORKING

No uncaught reference error while accessing let variable outside code block?

While learning javascript, I came across 2 different code snippets and I am confused about the scoping of variables declared using let/const. I know that variables declared using let/ const are block-scoped, meaning you can’t access them outside the block in which they are declared.

The following two snippets contradict each other, why is that so?

Snippet 1: ReferenceError as expected

const  calculateArea = function(radius){
  let area = 3.14 * radius ** 2;
  console.log(area);
}
console.log(area)

Output of snippet 1:

ReferenceError: area is not defined
    at <anonymous>:12:13
    at mn (<anonymous>:16:5455)

Snippet 2: Why no error???

 let age = 30;
 if(true){
    let age = 40;
  let name = 'Peter';
  console.log('Inside if block: ', name, age);
 }
  console.log('Outside if block: ', name, age);

Output of snippet 2:

Inside if block: 
Peter
40
Outside if block: 
30

Why is there space before age while logging outside if block statement to console?
Why was there no reference error this time?

hide cursor on class

on the website https://florianwmueller.com/work-alternative/ (a testpage) I have several images with the class .no-cursor. Then I have this little javascript below:

<script>
var elements = document.getElementsByClassName("no-cursor");
var style;

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener("mouseover", function() {
        style = document.createElement("style");
        style.innerHTML = "body.cursor-element-shape a { cursor: none !important; } .wpcc-active > .wpcc-cursor { display: none !important; }";
        document.head.appendChild(style);
    });
  
    elements[i].addEventListener("mouseleave", function() {
        document.head.removeChild(style);
    });
}
</script>

The goal is that this script prevents any mouse pointer from being visible when hovering the corresponding images. This has worked well so far, but after an update of the plugin “Custom Cursor” it no longer works. Can you tell me why?
The goal is that this script prevents any mouse pointer from being visible when hovering the corresponding images, also the custom cursor. This has worked well so far, but suddenly not anymore. Anyone any idea?

React crashes after updating text input field a second time

I have a component where users can enter text into an input field

import { useState } from "react";

export function App() {
    const [txt, setTxt] = useState("");

    return (
        <input value={txt} onInput={(e) => { setTxt(() => e.currentTarget.value); }} />
    );
}

Expected behaviour:

The input field should display the value of txt. Whenever the user types the onInput event should trigger and update the value of txt.

Actual behaviour

The code crashes after triggering the onInput event for the second time. I get errors like

Uncaught TypeError: Cannot read properties of null (reading 'value')
    at <anonymous>:41:36
    at basicStateReducer (<anonymous>:12325:51)
    at updateReducer (<anonymous>:12418:32)
    at updateState (<anonymous>:12654:20)
    at Object.useState (<anonymous>:13444:26)
    at useState (<anonymous>:1114:31)
    at App (<anonymous>:37:51)
    at renderWithHooks (<anonymous>:12163:28)
    at updateFunctionComponent (<anonymous>:15206:30)
    at beginWork (<anonymous>:16602:24)

and

The above error occurred in the <App> component:

    at App (<anonymous>:37:51)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

What is wrong with the code?

Undefined Usernames Issue in Django Channels WebSocket Consumer

I have created django consumers.py and a frontend in html and css to disply messages sent by a user, the profile picture of the sender and the username of the sender but anytime i open the browser, the message displays well but the username appears as undefined . eg @Undefined: How are you

this is my consumers.py

`User = get_user_model()

class DiscussionRoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = f"discussion_room_{self.room_name}"

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

        # Get or create the VirtualRoom instance based on the provided room_name
        virtual_room = await self.get_virtual_room()

        if virtual_room is not None:
            # Send existing messages and old messages to the new user
            old_messages = await self.get_old_messages(virtual_room)
            for message in old_messages:
                await self.send(text_data=json.dumps({
                    'message': message['content'],
                    'user_id': message['user'],
                    'user_picture': await self.get_user_profile_picture(message['user']),
                }))

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        user_id = self.scope["user"].id

        # Get the VirtualRoom instance based on the extracted room name asynchronously
        virtual_room = await self.get_virtual_room()

        # Check if the VirtualRoom instance exists
        if virtual_room:
            # Save message to the database with the VirtualRoom instance asynchronously
            await self.save_interaction_to_database(user_id, virtual_room, message)

            # Send message to the room group
            user_picture = await self.get_user_profile_picture(user_id)
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat.message',
                    'message': message,
                    'user_id': user_id,
                    'user_picture': user_picture,
                }
            )
        else:
            # Handle the case where the VirtualRoom does not exist
            print(f"VirtualRoom with slug '{self.room_name}' does not exist.")


    # Receive message from the room group
    async def chat_message(self, event):
        message = event['message']
        user_id = event['user_id']
        user_picture = event['user_picture']

        # Send the message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message,
            'user_id': user_id,
            'user_picture': user_picture,
        }))`


and this is my frontend:
<!DOCTYPE html>
{% load static %}
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/discussionroom.css' %}">
    <title>Discussion Room</title>
</head>
<body>
<div id="discussion-room">
    <div id="chat-box">
        {% for message in messages %}
            <div>
                <img src="{{ message.user_picture.url|default:'/static/images/avatar.svg' }}" alt="User Picture" style="width: 30px; height: 30px;">
                <strong>{{ message.username }}:</strong>
                {{ message.message }}
            </div>
        {% endfor %}
    </div>

    <input type="text" id="message-input" placeholder="Type your message...">
    <button onclick="sendMessage()">Send</button>
</div>

<script>
    // Get the room name from the URL
    const pathArray = window.location.pathname.split('/');
    const roomNameIndex = pathArray.indexOf('discussions') + 1;
    const roomName = pathArray[roomNameIndex].split('@')[1];

    // Log the extracted room name
    console.log('Extracted room name:', roomName);

    // Create a new WebSocket connection
    const socket = new WebSocket(`ws://${window.location.host}/ws/discussions/${roomName}/`);

    socket.onmessage = function(event) {
        const data = JSON.parse(event.data);
        displayMessage(data.user_picture, data.message);
    };

    function sendMessage() {
        const message = document.getElementById('message-input').value;
        if (message.trim() !== '') {
            socket.send(JSON.stringify({'message': message}));
            document.getElementById('message-input').value = '';
        }
    }
    function displayMessage(userPicture, message) {
    console.log('Received user picture:', userPicture);

    const messageDiv = document.createElement('div');

    // Set the userPicture URL
    const imageUrl = userPicture || '/static/images/avatar.svg';

    //console.log('Selected image URL:', imageUrl);

    const imgElement = new Image();
    imgElement.src = imageUrl;

    // Add an event listener to handle image load errors
    imgElement.addEventListener('error', function() {
        //console.warn('Error loading image. Using default avatar.');
        messageDiv.innerHTML = `<img src="/static/images/avatar.svg" alt="Default Avatar" style="width: 30px; height: 30px;"> ${message}`;
        document.getElementById('chat-box').appendChild(messageDiv);
    });

    // Add an event listener to handle image load success
    imgElement.addEventListener('load', function() {
        imgElement.className = 'user-profile-img'; // Add this line
        messageDiv.innerHTML = `<img src="${imageUrl}" alt="User Picture" style="width: 30px; height: 30px;  border-radius: 50%; object-fit: cover; "> ${message}`;
        document.getElementById('chat-box').appendChild(messageDiv);
    });
}

</script>

</body>
</html>