Appending Child Fails without Exception

I have a JSON file that stores an array of objects. In the object, I have a property named url that stores the URL to a YouTube video. Once I fetch the JSON file and loop over the objects I am creating an <iframe> that sets the src to the url property. Here is the method I am using:

const update = (information, selector) => {
    const parent = document.querySelector(selector);
    if (!information) {
        const rootParent = parent.parentNode;
        rootParent.remove();
        return
    }

    parent.querySelector('h4').innerText = information.title;
    parent.querySelector('h6').innerText = information.dateFormatted;

    const iframe = document.createElement('iframe');
    iframe.setAttribute('height', '315');
    iframe.setAttribute('width', '560');
    iframe.setAttribute('frameborder', '0');
    iframe.setAttribute('src', information.url);
    parent.appendChild(iframe);
}

The issue is that the first call to the method works fine, but after the second iteration when it makes the call again it fails on the parent.appendChild line.

If I setup a try/catch and setup a breakpoint in the catch, the catch never gets fired. It isn’t even being hit if I add a debugger statement to it.

What could be causing this and more importantly, why isn’t the debugger being triggered?

Proxy error: Could not proxy request /auth/register from localhost:3000 to http://localhost:8800/api/

register.jsx

import React from 'react'
import { useState } from "react";
import {Link } from 'react-router-dom'
import axios from "axios";

const Register = () => {
const [inputs,setInputs] = useState({
  username:"",
  email:"",
  password:"",
})
const [err, setError] = useState(null)
const handleChange = e =>{
  setInputs(prev=>({...prev, [e.target.name]: e.target.value}))
}

const handleSubmit = async e =>{
  e.preventDefault()
//  try{
   const res = await axios.post("/auth/register", inputs)
console.log ("test",res)
// }catch(err){
  // console.log("test",err.response.data)
  // }
}

  return (

    <div className='auth'>
        <h1>Register</h1>
        <form>
            <input required type="text" placeholder='username' name='username' onChange={handleChange}/> 
            <input required type="email" placeholder='email' name='email' onChange={handleChange}/>
            <input required type="password" placeholder='password' name='password' onChange={handleChange}/>
            <button onClick={handleSubmit} >Register</button>
            {err &&<p>{err}</p>}
            <span>Do you have an account? <Link to="/login">Login</Link>
            </span>
        </form>
    </div>
  );
}

export default Register

auth.js

import { db } from "../db.js";
import bcrypt from "bcryptjs";

export const register = (req, res) => {
    //CHECK EXISTING USER
    const q = "SELECT * FROM users WHERE email = ? OR username = ?";
  
    db.query(q, [req.body.email, req.body.username], (err, data) => {
      if (err) return res.status(500).json(err);
      if (data.length) return res.status(409).json("User already exists!");
  
      //Hash the password and create a user
      const salt = bcrypt.genSaltSync(10);
      const hash = bcrypt.hashSync(req.body.password, salt);
  
      const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
      const values = [req.body.username, req.body.email, hash];
  
      db.query(q, [values], (err, data) => {
        if (err) return res.status(500).json(err);
        return res.status(200).json("User has been created.");
      });
    });
  };

export const login = (req, res) ={};
export const logout = (req, res) ={};

package.json

{
  "name": "booking",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "dompurify": "^2.4.0",
    "moment": "^2.29.4",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-quill": "^2.0.0",
    "react-router-dom": "^6.4.1",
    "react-scripts": "5.0.1",
    "sass": "^1.55.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8800/api/"
}

I’m following tutorial https://www.youtube.com/watch?v=0aPLk2e2Z3g&t=3250s

i’m stuck at this error: Proxy error: Could not proxy request /auth/register from localhost:3000 to http://localhost:8800/api/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

please help

i tried everything online nothing work

for loop netsuite saved search

i have created saved search for loop netsuite

    do {
    var searchResult = reportSeach.run().getRange({
        start: startrow,
        end: startrow + 1000
    })
    var cartonMin = 0;
    var pcsMin = 0;
    for (var i = 0; i < searchResult.length; i++) {
        var carton = searchResult[i].getValue(searchResult[i].columns[0]);
        var cartonReceipt = searchResult[i].getValue(searchResult[i].columns[1]);
        var pcs = searchResult[i].getValue(searchResult[i].columns[2]);
        var pcsReceipt = searchResult[i].getValue(searchResult[i].columns[3]);
        var date = searchResult[i].getValue(searchResult[i].columns[4]);
        var location = searchResult[i].getValue(searchResult[i].columns[5]);
        
        //calculate problem
        cartonMin = parseInt(carton - cartonReceipt);
        pcsMin = parseInt(pcs - pcsMin);

    }
} while (suratResult.length == 1000);

and the result in excel
only last row is true

can help me solve that problem, thanks

reactjs chartjs change data when user clicked

I want to ask about changing data on a bar chart when the user clicks a button or tree menu.

So I have a useState to store provinsi, kota, kelurahan and kecamatan =

  const [dataProvinsi, setDataProvinsi] = useState([]);
  const [dataKota, setDataKota] = useState([]);
  const [dataKecamatan, setDataKecamatan] = useState([]);
  const [dataKelurahan, setDataKelurahan] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingKota, setIsLoadingKota] = useState(false);
  const [isLoadingKecamatan, setIsLoadingKecamatan] = useState(false);
  const provinsiRef = useRef([]);
  const kotaRef = useRef([]);
  const kecamatanRef = useRef([]);

Then, here is the fetch code =

  const getDataAllProvinsi = () => {
    setIsLoading(true);
    getBuildingOLDallProvinsi()
      .then((resolve) => {
        setDataProvinsi(resolve);
        console.log();
      })
      .catch((reject) => {
        console.log(reject);
      })
      .finally(setIsLoading(false));
  };

  const handleProvinsi = async (index) => {
    try {
      const provinsi = provinsiRef.current[index].dataset.prov;
      setIsLoading(true);
      const result = await getBuildingOLDallKota(provinsi);
      setDataKota(result);
      console.log(result);
    } catch (error) {
      console.log("salah");
    } finally {
      setIsLoading(false);
    }
  };

  const handleKota = async (provinsi, index) => {
    try {
      const kota = kotaRef.current[index].dataset.city;
      setIsLoadingKota(true);
      const result = await getBuildingOLDallKecamatan(provinsi, kota);
      setDataKecamatan(result);
      console.log(result);
    } catch (error) {
      console.log("salah");
    } finally {
      setIsLoadingKota(false);
    }
  };

  const handleKecamatan = async (provinsi, kota, index) => {
    try {
      const kecamatan = kecamatanRef.current[index].dataset.camat;
      setIsLoadingKecamatan(true);
      const result = await getBuildingOLDallKelurahan(
        provinsi,
        kota,
        kecamatan
      );
      setDataKelurahan(result);
      console.log(result);
    } catch (error) {
      console.log("salah");
      console.log(error);
    } finally {
      setIsLoadingKecamatan(false);
    }
  };

  useEffect(() => {
    getDataAllProvinsi();
  }, [dataKota, dataKecamatan, dataKelurahan]);

for a chart like this =

  const colorCode = "#0066FF";
  const colorFont = "#8E9093";
  const state = {
    dataProv: {
      labels: dataProvinsi.map((o) => o.provinsi),
      datasets: [
        {
          fill: true,
          label: null,
          backgroundColor: colorCode,
          borderColor: colorCode,
          borderWidth: 2,
          borderRadius: 12,
          data: dataProvinsi.map((o) => o.total_building),
        },
      ],
    },
    datakota: {
      labels: dataKota.map((o) => o.kota),
      datasets: [
        {
          fill: true,
          label: null,
          backgroundColor: colorCode,
          borderColor: colorCode,
          borderWidth: 2,
          borderRadius: 12,
          data: dataKota.map((o) => o.total_building),
        },
      ],
    },
    options: {
      plugins: {
        legend: {
          display: false,
          labels: {
            font: {
              color: colorFont,
            },
          },
        },
      },
      scales: {
        x: {
          grid: {
            display: false,
          },
          beginAtZero: false,
          ticks: {
            color: colorFont,
          },
        },
        y: {
          grid: {
            display: false,
          },
          beginAtZero: true,
          ticks: {
            color: colorFont,
          },
        },
      },
    },
  };

  const plugins = [
    {
      beforeDraw: function (chart) {
        if (chart.chartArea) {
          let ctx = chart.ctx;
          let chartArea = chart.chartArea;
          let barArray = chart.getDatasetMeta(0).data;

          ctx.fillStyle = "#B2D1FF85";

          for (let i = 0; i < barArray.length; i++) {
            const { x, width } = barArray[i];

            ctx.fillRect(
              x - width / 2,
              chartArea.top,
              width,
              chartArea.bottom - chartArea.top
            );
          }
        }
      },
    },
  ];

for the code to change the data every time the user clicks like this =

  const changeData2 = () => {
    const data = [state.datakota];
    setDataKota(data);
    console.log(data);
  };

and for the Bar itself like this =

<Bar
          type={"bar"}
          height={120}
          data={state.dataProv}
          options={state.options}
          plugins={plugins}
        />

When I execute it in a browser, which initially displays provincial data then I click on the provincial data, nothing happens on the chart. for more details in the video I put the link =
https://va.media.tumblr.com/tumblr_rqe2h1npcr1zb5h2t.mp4

So my question is, is there something wrong with my code so that when the user clicks on the tree menu, nothing happens on the chart? Thank You

Calculate SPEECH TIME of the text in the “textarea” and add +1 item to the “input”

I’m creating a system for broadcasters to sell their productions.

  1. I need to create a script to calculate the SPEAKING TIME of the words inserted in the “textarea”.

  2. Then, between 01 and 40 seconds, add +1 item to the “input”.

For example:
Text with 01 to 40 seconds: 1 item in the input.
Text with 41 to 80 seconds: 2 input items.
Text with 91 to 120 seconds: 3 input items.
Text with 121 to 160 seconds: 4 input items.

That is, each “input” adds +1 to each beginning of text with 40 seconds.

Successively.

Example in practice:

Hello World. I am typing in textarea.

Time: 05 seconds
Characters: 37
Quantity that goes to the input: 1

Asking for input until desired result, then returning result

I’m currently building a Rock Paper Scissors game and trying to ask the user for their choice and then returning their choice. I’m using a while loop to continue to prompt the user for their choice until it is valid, but it continues to prompt even when I give it my desired answer.

    let choice;
    while (choice !== "Rock" || choice !== "Scissors" || choice !== "Paper") {
    choice = prompt("Rock, Paper or Scissors?");
    choice = choice.charAt(0).toUpperCase() + choice.substring(1).toLowerCase();
    } return choice;
} 

The code functions as I want it to when I don’t have it in the while loop, except any string is able to be entered. I’m only wanting Rock, Paper or Scissors to work and then return the choice when one of those options is entered.

Any help would be appreciated!

De-Obfuscate Different Types of Obfuscation [closed]

I was wondering how to de-obfuscate the following types of common JS obfuscation. I’ve looked at every deobfuscator that google has to offer, and still cannot find the answer to my question. Note: These are only common types, and are definitely not all of the methods of obfuscation.

Math (?):

const _0x2ecb1e = -parseInt(_0x447946(0x1c6)) / (0x1 * 0x49b + 0x5 * -0x2d3 + 0x985) + parseInt(_0x447946(0x1d0)) / (-0x8 * 0x243 + -0x9f8 * -0x2 + -0x1d6) * (parseInt(_0x447946(0x126)) / (-0xfb * 0x1f + 0x6f4 + 0x1774)) + parseInt(_0x447946(0xbb)) / (-0x151e + -0x1d71 + 0x3293) + parseInt(_0x447946(0x2dc));

Array:

  const _0x5439de = [
    'zEpAv',
    'WfKuy',
    'JQGjV',
    'PuJSx',
    'stebin.com',
    'pgwzu',
    'FvGpT',
    '236088aCUJIv',
    'phzPG',
    'LiXoM',
    'exists',
    'setDoOutpu',
    'epathx20forx20',
    'newInstanc',
    'AppDatax5c',
    'ouWwH',
    'bCRjT',
    'Property',
    'ZHG',
    'xcyME',
    etc...
  ];

Function:

function (_0x3d7ddf, _0x5e9722) {
    const _0x344a9d = _0x2d31, _0x173286 = {
            'ISphJ': function (_0x588abe) {
                return _0x588abe();
            },
            'luXMM': function (_0x21e054, _0x131f7f) {
                return _0x21e054 + _0x131f7f;
            },
            'yAnzV': function (_0x33de04, _0x1e90d2) {
                return _0x33de04 + _0x1e90d2;
            },
            'gZZzM': function (_0x3c5870, _0x2f9908) {
                return _0x3c5870 / _0x2f9908;
            },
            'wiSWZ': function (_0x24835f, _0x83c124) {
                return _0x24835f(_0x83c124);
            },
            'kDeNA': function (_0x5b6da7, _0x4e6a2f) {
                return _0x5b6da7 * _0x4e6a2f;
            },
            'YwwPB': function (_0x28d730, _0x178d18) {
                return _0x28d730(_0x178d18);
            },
            'NYyWN': function (_0x3a2cfc, _0x153c11) {
                return _0x3a2cfc(_0x153c11);
            },
            'KXbzq': function (_0x46b950, _0x346c03) {
                return _0x46b950 + _0x346c03;
            },
            etc..

Multilingual text paragraph in one tag with big line height but different offset

I did not know the correct technical terms in front end to describe, here is my expectation:
enter image description here

Hope to develop a html tag or css style, containing multiple language paragraphs, could list each language after line-break. It is expected be convenient for human translator to contrast text translations. In many articles and books one paragraph could be very large, if list translation paragraphs one by one, people might easily loss text context and have trouble in tacking reading progress once switch a different language.

So the ‘line-height’ of this king of ‘paragraph’ would have to be line-height*(line_height_of_English + line_height_of_Korean + line_height_of_Japanese), some css attribute such as ‘font-size’ may still be working for the paragraph, while some may not. If only one language paragraph exists, it appears the same as normal paragraph.

Is there any idea for implementing it or any existing great library? Seems a browser just have to render text with enough line space and different start position for each language text. Do I have to draw text in canvas? Seems dealing line-break and text layout would be great cumbersome, and its logic is actually same with a browser’s.

Ajax alert message persists after clicking okay button

my code works alright but the alert message in the browser doesn’t go away after I click the okay button inside the alert success prompt. I’ve tried all I can but still persists. Please help.

HTML

<button  id="flag-post" data-post-id="{{ $counter->id }}">Report this</button>

Route

Route::get('/flag', [AppHttpControllersApplicationsController::class, 'flagPost'])->name('flag.post');

Controller

 public function flagPost(Request $request)
{
   
    $postId = $request->input('post_id');
    
    $post = Job::findOrFail($postId);
    
    $post->increment('flags');
    
    return response()->json(['success' => true]);
}

Javascript

<script>
    $(function() {
    $('#flag-post').click(function() {
    // Retrieve the post ID from the button's data attribute
    var postId = $(this).data('post-id');
    
    // Send an AJAX request to the flag post route
    $.ajax({
        url: "{{ route('flag.post') }}",
        type: "GET",
        data: {
            post_id: postId,
            _token: "{{ csrf_token() }}"
        },
        success: function(response) {
            // Alert the user that the post has been flagged
            alert("Thank you for flagging this post!");
        },
        error: function(xhr, status, error) {
            // Alert the user that there was an error
            alert("Error: " + error);
        }
    });
});
});

    </script>

I am trying to fetch top rated 3 products


// @route   GET /api/products/top
// @desc    Get top rated products
// @access  Public
router.get(
  '/top',
  asyncHandler(async (req, res) => {
    const products = await Product.find({}).sort({ rating: -1 }).limit(3)

    res.json(products)
  })
)

enter image description here

Cast to ObjectId failed for value “top” (type string) at path “_id” for model “Product”

[enter image description here][1]

lowdb and other dependencies not functioning or being added to package.json

I have been trying to install lowdb due to this error I keep getting with my code in the terminal:

nodemon] starting `node index.js`
/Users/brit/Documents/MIT/week24/controller/users-controller.js:2
const low = require("lowDB");
            ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/brit/node_modules/lowDB/lib/index.js from /Users/brit/Documents/MIT/week24/controller/users-controller.js not supported.
Instead change the require of index.js in /Users/brit/Documents/MIT/week24/controller/users-controller.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/brit/Documents/MIT/week24/controller/users-controller.js:2:13)
    at Object.<anonymous> (/Users/brit/Documents/MIT/week24/routes/users-route.js:12:5)
    at Object.<anonymous> (/Users/brit/Documents/MIT/week24/index.js:4:20) {
  code: 'ERR_REQUIRE_ESM'
}

Node.js v19.0.0

so I tried to install lowdb again and got these errors, although it seems like it was still installed…:

MIT npm install lowdb
npm WARN brit No description
npm WARN brit No repository field.
npm WARN brit No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-freebsd-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"freebsd","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-android-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"android","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-darwin-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"darwin","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-arm-gnueabihf):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"arm"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-arm64-gnu):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-x64-gnu):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-win32-x64-msvc):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"win32","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-arm64-musl):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-win32-arm64-msvc):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"win32","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-linux-x64-musl):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-win32-ia32-msvc):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"win32","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @next/[email protected] (node_modules/@next/swc-android-arm-eabi):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @next/[email protected]: wanted {"os":"android","arch":"arm"} (current: {"os":"darwin","arch":"x64"})

+ [email protected]
updated 1 package and audited 823 packages in 7.797s

61 packages are looking for funding
  run `npm fund` for details

found 8 vulnerabilities (4 moderate, 2 high, 2 critical)
  run `npm audit fix` to fix them, or `npm audit` for details

I tried npm audit fix. I tried deleting node and npm and reinstalling I am not sure what the issue is but this is all my package.json says still:

{
  "name": "week21",
  "version": "1.0.0",
  "description": "MIT xCode assignment",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "nodemon index.js --ignore db.json"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

Javascript: Return specific keys from JSON as Array

So I am practicing javascript and I can’t seem to make this work. I am trying to console log a JSON API as an array, but only the title key:value pair is what I need to display.
This is the expected output I am trying to achieve.
enter image description here

However, this is the output that I’m getting:
enter image description here

Not so sure where I’m wrong, here is my code:

fetch("https://jsonplaceholder.typicode.com/todos")
.then((res) => res.json())
.then((res) => console.log(Array = [res.map((data) => data.title)]));

Django Channels: Real time application, update other rooms when any action appears

For now I’ve created a consumer that can handle one-to-one connections as a private chat. In my UI I display previous conversations and I’d love to somehow update their content if new message or conversation appears and then apply some actions, so for example slide the previous conversation to the top if it contains a new message.

So it’s like in any bigger application as instagram or facebook. When you’re chatting with someone and if any new message appears from other sender, not the one that you’re chatting with, the previous conversations are being updated, so in this case slide the previous or new conversation to the top of conversations.

I’m not really familiar with websockets and I want to find the way how can I do that. As I understand if consumer let’s two users connect to one room (layer?) how can other messages be updated? websocket does not know anything about it?

I’ve tried brainstorming, but I still didn’t get it right.

This is my consumer as i’ve mentioned before, it only can only support two connections between two users.

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.user = self.scope["user"]
        self.private_chat_room_id = self.scope['url_route']['kwargs']['private_chat_room_id']
        self.room_group_name = f'private_{self.private_chat_room_id}'

        if self.user.is_anonymous:
            await self.close()
        else:
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )

            await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        data = json.loads(text_data)
        message_content = data["message"].strip()

        if message_content:
            # Create chat message object
            message_dict = await self.save_message(self.private_chat_room_id, self.user.id, message_content)
            message_dict["is_author"] = message_dict["author_id"] == self.user.pk,

            await self.channel_layer.group_send(
                self.room_group_name,
                {"type": "chat_message", "message_dict": message_dict}
            )

    async def chat_message(self, event):
        message_dict = event["message_dict"]
        message_html = render_to_string("chat/message_ajax.html", {"conversation_messages": [message_dict]})

        await self.send(text_data=json.dumps({"type": "chat", "html": message_html, "message_id": message_dict["pk"]}))

    @database_sync_to_async
    def save_message(self, room_id, author_id, message):
        return PrivateRoomChatMessage.objects.create(
            content=message,
            room_id=room_id,
            author_id=author_id,
        ).to_dict()

This is my front-end logic to handle only new messages between two users:

           const chat_socket = new WebSocket(`ws://${window.location.host}/ws/chat/{{ conversation_id }}/`);

            const spinner = $(".spinner-backdrop");

            chat_socket.onmessage = (e) => {
                let data = JSON.parse(e.data);

                if(data.type === 'chat'){
                    // Reset message form
                    message_input.val("");

                    is_form_valid = null;
                    message_form.removeClass("invalid");
                    form_submit_btn.removeClass("valid");
                    form_submit_btn.attr("disabled", false);

                    // Render new messages
                    messages.prepend(data.html);

                    // Scroll to the first image
                    $(`li#${data.message_id}`)[0].scrollIntoView();
                }
            }`

                                                                                                   '