how to add object into array with hook state in react js

I’m trying to set the id property of a state object based on the id attribute of the button I clicked, and then append it into a state array and then store it in the localstorage. but there are weird things happening in my code:

  1. when I clicked the 1st button, the console.log shows the id value of the 1st button (5) but the state object were still empty

  2. then I clicked on the 2nd button, the console.log shows the id value of the 2nd button (12) but the state object now contains the value from the 1st button (5)

  3. then I called the 3rd button, the console.log shows the id value of the 3rd button (100) but the state object contains the value of the 2nd button (12)

  4. why are the Buttons still look like a regular/default button even though I already added the react-bootstrap dependency, imported the Button component, and applied the variant="link" in the Button?

here’s my code (and the codesandbox)

import { useState, useEffect } from "react";
import { Button } from "react-bootstrap";

export default function App() {
  const [cartList, setCartList] = useState([]);
  const [cartItem, setCartItem] = useState({});

  useEffect(() => {
    let localCart = localStorage.getItem("cartList") || "[]";
    console.log("localcart", localCart);
    if (localCart) {
      localCart = JSON.parse(localCart);
    }
    setCartList(localCart);
  }, []);

  const handleClick = (e, item) => {
    e.preventDefault();

    const arr = e.target.id.split("-");
    const selectID = arr[1];
    console.log("selectID", selectID);
    setCartItem({ ...cartItem, id: selectID });
    console.log("cartItem", cartItem);

    let itemIndex = -1;
    console.log("cartlist", cartList);
    for (let i = 0; i < cartList.length; i++) {
      if (cartItem && selectID === cartList[i].id) {
        itemIndex = i;
      }
    }
    if (itemIndex < 0) {
      console.log("added to cartList on index", itemIndex, cartItem);
      setCartList([...cartList, cartItem]);
      localStorage.setItem("cartList", JSON.stringify(cartList));
    }
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Button
        variant="link"
        id="item-5"
        onClick={(e) => handleClick(e, cartItem)}
      >
        item no.5
      </Button>
      <Button
        variant="link"
        id="item-12"
        onClick={(e) => handleClick(e, cartItem)}
      >
        item no.12
      </Button>
      <Button
        variant="link"
        id="item-100"
        onClick={(e) => handleClick(e, cartItem)}
      >
        item no.100
      </Button>

      <div>
        {cartList.length > 0 ? (
          cartList.map((item, index) => <div key={index}>{item.id}</div>)
        ) : (
          <div>there is no data here</div>
        )}
      </div>
    </div>
  );
}

How to change background Image with DOM and JavaScript


Hi Everyone,
I am a beginner working on a small project in which I am facing an issue related to the background image (how I can change the background image using DOM and Javascript). I Have tried a few ways but am still on the problem side. I have used JavaScript function (random_image_picker(min,max)) for getting random image from Image_gallery. Everything going well until when I clicked on background_theme btn, the background image was supposed to be changed but not working. Every help would be appreciated.
Thanks
HTML Tag…

..Background Image….

   <script>
        const image_gallery = ['https://img.playbuzz.com/image/upload/ar_1.5,c_pad,f_jpg,b_auto/q_auto:good,f_auto,fl_lossy,w_480,c_limit,dpr_1/cdn/2c2dd0ea-8dec-4d49-8a95-f7b18f0b7aed/df312655-1d96-457d-88f4-cfc93c580d1d_560_420.jpg',
            'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTwpR0X1hmpt4Kd2WviLXQGPrnUllW2UoLgtoWBoesgtFtSPFCF808bibJ8K2VhHRCki48&usqp=CAU',
            'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxmLTuD78jeZaVR3I_xfIuvmE4tse_JuhGjQ&usqp=CAU',
            'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSxWrBodkwbTlxbMexeQCOneifPHaOUoTFwPA&usqp=CAU',
            'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtQMwmsMjdYfF0W0cyMPX673aKVK3m8sSDjg&usqp=CAU']
        function random_image_picker(min, max) {
            let a = Math.floor(Math.random() * (max - min + 1) + min);
            return image_gallery[a];
        }
        let background_theme = document.querySelector('#background_theme');
        let main = document.getElementsByTagName('main');
        background_theme.addEventListener('click',function(){
            main.style.backgroundImage = URL(random_image_picker(0,4))
        })


    </script>

fetching data through env.local file gives an error “Failed to load resource: the server responded with a status of 401”

I have a problem when i try to fetch data through my env file i get an error “Failed to load resource: the server responded with a status of 401 ()”
but when i fetch data without using env.local file and use my api key directly in const variable everything works fine. But i want to make the env local file call to work.

My env.local file

API_KEY=3retkjdkfgjfd95659 (MADE IT UP FOR THE POST)

My utils folder /requests.js

const API_KEY = process.env.API_KEY;
//const API_KEY = "3retkjdkfgjfd95659" the code works only when i use this variable
const requests = {
  fetchTopRated: {
    title: "Top Rated",
    url: `/movie/top_rated?api_key=${API_KEY}&language=en-US`,
  },}

My axios file

const instance = axios.create({
  baseURL: "https://api.themoviedb.org/3/",
});

export default instance;

Banner file

function Banner() {
  const [movie, setMovie] = useState([]);
  useEffect(() => {
    async function fetchData() {
      const request = await axios.get(requests.fetchTopRated.url);
      setMovie(
        request.data.results[
          Math.floor(Math.random() * request.data.results.length - 1)
        ]
      );
      return request;
    }
    fetchData();
  }, []);

SequelizeDatabaseError Error: Table doesn’t exist

I am trying to create tables using Sequelize programitacally but its continuously showing that the table does not exist, even after using {force:true}. Please do have a look at the code below and kindly help.

App.js

const express = require("express");
const app = express();
const addCompany = require("./controller/routes/addCompany");
const sqlize = require(".//../data/database/database")
const { Company, company } = require("../src/model/companyData")

const {salesUser, team} = require("../src/model/teamData")
const salesTeam = require("./controller/routes/salesTeam")

app.set("view engine", "ejs");
app.use(express.static("views"));

app.use("/company", addCompany.router);
app.use("/team", salesTeam.router)


sqlize
  .sync({ force: true })
  .then(result => {
  // console.log(result);
  app.listen(3000);
  })
  .catch(err => {
  console.log(err);
});

MODELS :
companyData.js

const { Sequelize, DataTypes } = require('sequelize');

const sqlize = require("../../data/database/database")


const company = sqlize.define('Company', {
    // Model attributes are defined here
    cname: {
        type: DataTypes.TEXT,
        allowNull : false
    },
    id: {
        type: DataTypes.STRING,
        allowNull: false,
        primaryKey : true
    },
    revenue: {
        type: DataTypes.DOUBLE,
        allowNull : false
    },
    country: {
        type: DataTypes.STRING
    }
}
);

class Company {

    constructor(cname, id, revenue, country) {
        
        this.cname = cname
        this.id = id
        this.revenue = revenue
        this.country = country
    }
    
    
    async save() {

        //console.log(this)
        let newCompany = company.build(this);
        await newCompany.save();
        console.log('Saved to the database!');
       
    }
    
    async fetch() {
        
        let companyData = await company.findAll();
        //console.log(companyData)
        //console.log(companyData.every(el => el instanceof company));
        //console.log("All users:", JSON.stringify(companyData));
        let cData = JSON.stringify(companyData, null, 2)
        //console.log("CDATA +++++++++",JSON.parse(cData))
        let fetchData = []
        cData = JSON.parse(cData)
        cData.forEach(el => 
        fetchData.push({
            'cname': el.cname,
            'id': el.id,
            'revenue': el.revenue,
            'country': el.country
        }))
        //console.log(fetchData)
        return fetchData
    }

    async delete(id) {
        
        await company.destroy({ where: { id: id } });
    }

    async edit(newData) {
        let oldID = newData.oldID
        const entry = await company.findByPk(oldID);
        if (entry === null) {
        console.log('Not found!');
        } else {
        
            console.log(entry instanceof company); // true
            console.log(entry.dataValues)
            let oldID = newData.oldID
            delete newData.oldID
            console.log(newData)
            
            await company.update(
                
                   newData,
                
                {
                    where: {id: oldID}
                }
            );
            
            await this.fetch()
        }
        
    }

}


module.exports = {
    Company: Company,
    company: company
}

MODELS
teamData.js

const { Sequelize, DataTypes } = require('sequelize');

const sqlize = require("../../data/database/database")

const team = sqlize.define('salesTeam', {
    // Model attributes are defined here
    empName: {
        type: DataTypes.STRING,
        allowNull : false
    },
    empID: {
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey : true
    }
}
);




class salesUser {

    constructor(empName, empID) {
        
        this.empName = empName
        this.empID = empID
    }
    
    
    async save() {

        //console.log(this)
        let newUser = team.build(this);
        await newUser.save();
        console.log('Saved to the database!');
       
    }
    
    async fetch() {
        
       
        try {
            let salesUserData = await team.findAll()
          
            //console.log(companyData)
            //console.log(companyData.every(el => el instanceof company));
            //console.log("All users:", JSON.stringify(companyData));
            let sData = JSON.stringify(salesUserData, null, 2)
            //console.log("CDATA +++++++++",JSON.parse(cData))
            let fetchData = []
            sData = JSON.parse(sData)
            sData.forEach(el =>
                fetchData.push({
                    'empName': el.empName,
                    'empID': el.empID

                }))
            //console.log(fetchData)
            return fetchData
        }
        catch (err) {
            console.error(err)
        }
    }

    async delete(id) {
        
        await company.destroy({ where: { empID: id } });
    }

    async edit(newData) {
        let oldempID = newData.oldempID
        const entry = await company.findByPk(oldempID);
        if (entry === null) {
        console.log('Not found!');
        } else {
        
            console.log(entry instanceof team); // true
            console.log(entry.dataValues)
            let oldempID = newData.oldempID
            delete newData.oldempID
            console.log(newData)
            
            await team.update(
                
                   newData,
                
                {
                    where: {empID: oldempID}
                }
            );
            
            await this.fetch()
        }
        
    }

}

module.exports = {
    salesUser: salesUser,
    team: team
}

DATABASE
database.js

const Sequelize = require('sequelize');

const sqlize = new Sequelize('node-database', 'root', 'password', {
  dialect: 'mysql',
  host: 'localhost'
});

module.exports = sqlize;

ERROR I AM FACING :

……….
Executing (default): SELECT cname, id, revenue, country, createdAt, updatedAt FROM Companies AS Company;
Executing (default): SELECT empName, empID, createdAt, updatedAt FROM salesTeams AS salesTeam;
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^

Error
    at Query.run (D:Node.js FolderTest 1node_modulessequelizelibdialectsmysqlquery.js:52:25)
    at D:Node.js FolderTest 1node_modulessequelizelibsequelize.js:311:28
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async MySQLQueryInterface.select (D:Node.js FolderTest 1node_modulessequelizelibdialectsabstractquery-interface.js:407:12)
    at async Function.findAll (D:Node.js FolderTest 1node_modulessequelizelibmodel.js:1134:21)
    at async Company.fetch (D:Node.js FolderTest 1srcmodelcompanyData.js:63:27) {
  name: 'SequelizeDatabaseError',
  parent: Error: Table 'node-database.companies' doesn't exist
      at Packet.asError (D:Node.js FolderTest 1node_modulesmysql2libpacketspacket.js:728:17)
      at Query.execute (D:Node.js FolderTest 1node_modulesmysql2libcommandscommand.js:29:26)
      at Connection.handlePacket (D:Node.js FolderTest 1node_modulesmysql2libconnection.js:456:32)
      at PacketParser.onPacket (D:Node.js FolderTest 1node_modulesmysql2libconnection.js:85:12)
      at PacketParser.executeStart (D:Node.js FolderTest 1node_modulesmysql2libpacket_parser.js:75:16)
      at Socket.<anonymous> (D:Node.js FolderTest 1node_modulesmysql2libconnection.js:92:25)
      at Socket.emit (node:events:390:28)
      at addChunk (node:internal/streams/readable:315:12)
      at readableAddChunk (node:internal/streams/readable:289:9)
      at Socket.Readable.push (node:internal/streams/readable:228:10) {
    code: 'ER_NO_SUCH_TABLE',
    errno: 1146,
    sqlState: '42S02',
    sqlMessage: "Table 'node-database.companies' doesn't exist",
    sql: 'SELECT `cname`, `id`, `revenue`, `country`, `createdAt`, `updatedAt` FROM `Companies` AS `Company`;',
    parameters: undefined
  },
  original: Error: Table 'node-database.companies' doesn't exist
      at Packet.asError (D:Node.js FolderTest 1node_modulesmysql2libpacketspacket.js:728:17)
      at Query.execute (D:Node.js FolderTest 1node_modulesmysql2libcommandscommand.js:29:26)
      at Connection.handlePacket (D:Node.js FolderTest 1node_modulesmysql2libconnection.js:456:32)
      at PacketParser.onPacket (D:Node.js FolderTest 1node_modulesmysql2libconnection.js:85:12)
      at PacketParser.executeStart (D:Node.js FolderTest 1node_modulesmysql2libpacket_parser.js:75:16)
      at Socket.<anonymous> (D:Node.js FolderTest 1node_modulesmysql2libconnection.js:92:25)
      at Socket.emit (node:events:390:28)
      at addChunk (node:internal/streams/readable:315:12)
      at readableAddChunk (node:internal/streams/readable:289:9)
      at Socket.Readable.push (node:internal/streams/readable:228:10) {
    code: 'ER_NO_SUCH_TABLE',
    errno: 1146,
    sqlState: '42S02',
    sqlMessage: "Table 'node-database.companies' doesn't exist",
    sql: 'SELECT `cname`, `id`, `revenue`, `country`, `createdAt`, `updatedAt` FROM `Companies` AS `Company`;',
    parameters: undefined
  },
  sql: 'SELECT `cname`, `id`, `revenue`, `country`, `createdAt`, `updatedAt` FROM `Companies` AS `Company`;',
  parameters: {}
}
[nodemon] app crashed - waiting for file changes before starting... 

Get parentNode on change the CodeMirror

I have multiple div elements, each includes one codemirror element. I want to get id of div on changing codemirror inside.
I need your help. Any idea?

$(document).ready(function(){
    $(".code").each(function (i, editorEl) {
        CodeMirror.fromTextArea(editorEl, {
            lineNumbers: true,
            mode: "xml"
        }).on("change", function(editorEl) {
            console.log("HOW I GET THE PARENT ELEMENT ID HERE");
        });
    });
});
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.js"></script>

<div id="poo"><textarea class="code" mode="text/html"></textarea></div>
<div id="foo"><textarea class="code" mode="text/html"></textarea></div>
<div id="boo"><textarea class="code" mode="text/html"></textarea></div>
<!-- ... -->
<div id="nnn"><textarea class="code" mode="text/html"></textarea></div>

Property Assignment Expected Error in Java script when passing flask variables to charts

Hi i was tiring to get to use jinja variables in JS to create task the task is working but the terminal shows an error saying that “property assignment expected” and “Declaration or statement expected” but i am getting output correctly can you help me to resolve these errors i just want error free code.

<div class="mb-3 row">
<div class="mb-3 col">
  <canvas id="myChart" style="position: relative; width:100%;max-width:500px"></canvas>
</div>
<div class="mb-3 col">
<canvas id="myChart1" style="position: relative; width:100%;max-width:300px"></canvas>
</div>
<div class="w-100"></div>
<div class="mb-3 col">
<canvas id="myChart2" style="position: relative; width:100%;max-width:500px"></canvas>
</div>
<div class="mb-3 col">
<canvas id="myChart3" style="position: relative; width:100%;max-width:500px"></canvas>
</div>
</div>

<script type = "text/javascript">

xValues = {{label|safe}};
yValues = {{value|safe}};
pyValues = {{budget|safe}};
VValues = {{memb|safe}};
VyValues = {{val1|safe}};
sValues = {{subt|safe}};

var barColors = ["red", "green","blue","orange","brown","purple","pink"];
var barColors1 = ["#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"];

new Chart("myChart", {
type: "horizontalBar",
data: {
  labels: xValues,
  datasets: [{
    backgroundColor: barColors,
    data: yValues
  }]
},
options: {
  legend: {display: false},
  title: {
    display: true,
    text: "Allocated Hours for projects",
    type:"verticalBar"
  }
}
});

new Chart("myChart1", {
type: "doughnut",
data: {
datasets: [{
backgroundColor: barColors1,
data: pyValues
}]
},
options: {
title: {
display: true,
text: "Allocated budget project wise"
}
}
});

new Chart("myChart2", {
type: "bar",
data: {
  labels: VValues,
  datasets: [{
    backgroundColor: barColors,
    data: VyValues
  }]
},
options: {
  legend: {display: false},
  title: {
    display: true,
    text: "Allocated Hours for projects",
    type:"verticalBar"
  }
}
});

new Chart("myChart3", {
  type: "bar",
  data: {
    labels: sValues,
    datasets: [{
      backgroundColor: barColors,
      data: VyValues
    }]
  },
  options: {
    legend: {display: false},
    title: {
      display: true,
      text: "Allocated Hours for projects",
      type:"verticalBar"
    }
  }
});
</script>

Below is my error masseges

Property assignment expected.in all jinja variables assigned

How do I create a new HTML element from JavaScript? [duplicate]

I am beginner JavaScriptv developer, I am trying to develop a todo list app and I have been able to complete the design/frontend part of it. How do I create a new HTML element from JavaScript that gets the value from my input then uses that to create an HTML element while applying all the styles in my CSS.

// Theme Switch
const theme = document.getElementById("themeToggle");

theme.addEventListener('click', () => {
    document.body.classList.toggle('dark');

    if (document.body.classList.contains('dark')) {
        theme.src = "/images/icon-sun.svg"
    } else {
        theme.src = "/images/icon-moon.svg"
    }
});

// Input Value Todo
const todoInput = document.getElementById("input-todo");
const createTodo = document.getElementById("createTodo")

createTodo.addEventListener('click', (e) => {
        let value = todoInput.value;
        
})
@import url(https://fonts.googleapis.com/css?family=Josefin+Sans:100,200,300,regular,500,600,700);

:root {
    --header-desktop-image: url("images/bg-desktop-light.jpg");
    --header-mobile-image: url("images/bg-mobile-light.jpg");
    --theme-toggle-icon: url("images/icon-moon.svg");
  
    --bright-blue: hsl(220, 98%, 61%);
    --bg-color: hsl(0, 0%, 98%);
    --text-color: hsl(235, 19%, 35%);
    --todo-bg-color: #fff;
    --btn-text-color: hsl(236, 9%, 61%);
    --border-color: hsl(233, 11%, 84%);
    --hover-color: hsl(235, 19%, 35%);
    --shadow: rgba(0, 0, 0, 0.2);
}

.dark{
    --header-desktop-image: url("images/bg-desktop-dark.jpg");
    --header-mobile-image: url('images/bg-mobile-dark.jpg');
    --theme-toggle-icon: url("images/icon-sun.svg");

    --bright-blue: hsl(220, 98%, 61%);
    --bg-color: hsl(235, 21%, 11%);
    --text-color: hsl(234, 39%, 85%);
    --todo-bg-color: hsl(235, 24%, 19%);
    --cta-text-color: hsl(234, 11%, 52%);
    --border-color: hsl(237, 14%, 26%);
    --hover-color: hsl(236, 33%, 92%);
}

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    text-decoration: none;
    list-style: none;
    outline: none;
    text-decoration: none;
    font-family: "Josefin Sans", sans-serif;
}

body {
    background-color: var(--bg-color);
}

.header {
    width: 100%;
    height: 220px;
    background: var(--header-desktop-image);
    background-repeat: no-repeat;
    background-size: cover;
    position: absolute;
    z-index: -1;
}

main {
    display: flex;
    flex-direction: column;
    gap: 30px;
    padding: 50px 30px 20px;
}

main header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

main header .logo h1 {
    color: white;
    letter-spacing: 7px;
    font-weight: 700;
}

main header img {
    cursor: pointer;
    width: 26px;
    height: 26px;
}

form {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 2px;
    width: 100%;
    background-color: var(--todo-bg-color);
    padding: 0 9px;
    border-radius: 8px;

}

input[type="text"] {
    width: 100%;
    border: none;
    padding: 12px 8px;
    outline: none;
    font-size: 18px;
    background-color: var(--todo-bg-color);
}

.status{
    width: 18px;
    height: 17px;
    border-radius: 50%;
    border: 1px var(--text-color) solid;
    cursor: pointer;
}

ul {
    border-radius: 1vh;
    overflow: hidden;
}

ul .todo {
    width: 100%;
    padding: 16px;
    display: flex;
    align-items: center;
    list-style: none;
    border-bottom: 1px solid var(--border-color);
    background-color: var(--todo-bg-color);
    color: var(--text-color);
}

ul .todo .todo_name {
    margin-left: 12px;
}

ul .todo .todo_name span {
    font-size: 16px;
    color: var(--text-color);
}

ul .footer {
    width: 100%;
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    list-style: none;
    border-bottom: 1px solid var(--border-color);
    background-color: var(--todo-bg-color);
    color: var(--text-color);
}

ul .cta {
    margin-top: 30px;
    width: 100%;
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    list-style: none;
    border-bottom: 1px solid var(--border-color);
    background-color: var(--todo-bg-color);
    color: var(--text-color);
}

ul .cta span {
    cursor: pointer;
    color: var(--cta-text-color);
}

.delete_btn {
    cursor: pointer;
    display: block;
    margin-right: 0;
    margin-left: auto;
}

.status-background{
    background: url("images/icon-check.svg"), linear-gradient(hsl(192, 100%, 67%), hsl(280, 87%, 65%));
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}

.large_cta {
    display: none;
    cursor: pointer;
}

.clear_completed {
    cursor: pointer;
}

@media screen and (min-width: 768px) {
    main {
        margin: 0 auto;
        max-width: 80%;
    }

    .large_cta {
        display: block;
    }

    .large_cta span {
        margin-right: 15px;
    }

    li.cta {
        display: none;
    }
}

@media screen and (min-width: 960px) {
    main {
        margin: 0 auto;
        max-width: 60%;
    }

}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">
  <title>Todo app</title>
</head>
<body>
  <div class="header"></div>

  <main>
    <header>
      <div class="logo"><h1>TODO</h1></div>
      <img src="/images/icon-moon.svg" alt="sun-icon" id="themeToggle">
    </header>

    <form action="" class="form">
      <label for="input-todo" id="createTodo" class="status"></label>
      <input type="text" class="input-todo" id="input-todo" placeholder="Create a new todo...">
    </form>

    <ul>
      <li class="todo">
        <div class="status"></div>
        <div class="todo_name"><span>Need to charge phone</span></div>
        <div class="delete_btn"><img src="/images/icon-cross.svg" alt=""></div>
      </li>

      <li class="footer">
        <div class="items_left">
          <span class="left">5</span> 
          <span>items left</span>
        </div>

        <div class="large_cta">
          <span id="all">All</span>
          <span id="active">Active</span>
          <span id="Completed">Completed</span>
        </div>

        <div class="clear">
          <span class="clear_completed">Clear Completed</span>
        </div>
      </li>

      <li class="cta">
        <span id="all">All</span>
        <span id="active">Active</span>
        <span id="Completed">Completed</span>
      </li>
    </ul>
  </main>

  <script src="/main.js"></script>
</body>
</html>

The elements are being duplicated when adding them to container from local storage

I want to add some values to a container and save them in localstorage but when i click on the button to add them after the first time elements are being duplicated in the container not the localstorage. the weird thing is that when i reload the page the duplicates go out and the elements increament by the count of elements i added only here’s my code:

```
let divP = document.querySelector(".parent");
let input = document.querySelector("input");
let button = document.querySelector("button");
let container = document.getElementById("container");

let array = JSON.parse(localStorage.getItem("array")) || [];
let isUpdate = false;

function createElement() {
  array.forEach((arr, id) => {
    let div = document.createElement("div");
    div.classList.add("div");
    div.id = id;
    div.innerHTML = arr.title;
    container.appendChild(div);
  });
}
createElement();

button.addEventListener("click", (e) => {
  e.preventDefault();
  let title = input.value.trim();
  let id = Date.now();
  if (title || id) {
    let arrayInfo = { title, id };
    if (!isUpdate) {
      array.push(arrayInfo);
    } else {
      isUpdate = false;
    }
    localStorage.setItem("array", JSON.stringify(array));
    createElement();
  }
});

Coinbase api on production behavior is behaving differently from the the api on development (using the temporary accesstoken)

Results I’m getting on development is different from those I’m getting on production

For example
I do not get all the accounts a user has on production, I get all on development,

account id on development has the original id while on production, account id has the account name instead of the original id. Only BTC account has the original id, the rest has the name

And if I want to get just an account, I will need to get the account id

That means with this behavior on production, I cannot get any account except btc account.

Please anyone has the solution to this behavior or is having similar changes?

map is not function error, when loading page and useEffect fetching data from Firebase

I get data from firebase firestore. It returns “filter is not function and error”. I think it is problem because firstly runs LoadBooks function and after birngs Data from firestore. How can i fix it? Async? I can’t write it rightly or i dont know, just can’t do, need a help please.

*here isnt error if i fetch same data from JSON file.

**// Fetch Book to Home Page List**

  const [list, setList] = useState();

  useEffect(() => {
      const data = onSnapshot(collection(db, "Books"), (snapshot) => {
        setList(snapshot.docs.map((doc) => doc.data()));
      });
      return data;
  }, []);

**//search**
  const [search, setSearch] = useState("");
  **//Category filter**
  const [filter, setFilter] = useState("all");

  function LoadBooks() {
    // search
    const book = list.filter((val) => {
      if (search === "") {
        return val;
      } else if (val.title.toLowerCase().includes(search.toLowerCase())) {
        return val;
      }
    })
      // filter and map
      .map((item) => {
        if (item.category === filter) {
          return (
            <Book key={item.id} {...item} />
          );
        } else if (filter === "all") {
          return (
            <Book key={item.id} {...item} />
          );
        }
      })
    return book;
  }

  const book = LoadBooks();

Check and Uncheck Parent/Child Checkboxes using Jquery

I have to use group of checkboxes in my project.

This is how my HTML look like:

<table id="myTable">
<tr>
  <td>
    <label>
      <input type="checkbox" class="parent" name="mod[6]" value="1">
    </label>
  </td>
  <td><span>Parent Module</span></td>
  <td>
    <label>
      <input type="checkbox" name="mod[7]" value="1"> Sub Module
    </label>
    <label>
      <input type="checkbox" name="mod[8]" value="1"> Sub Module
    </label>
    <label>
      <input type="checkbox" name="mod[9]" value="1"> Sub Module
    </label>
  </td>
</tr>
<tr>.....</tr>
<tr>.....</tr>
</table>

Using this checkboxes, users can select their preferred parent and sub module selection.
When making that selection, it should work as follows.

  • When a parent is checked, all children are checked under it. (Parents
    and children are separated by a row on the table)
  • When a parent is unchecked, all children are unchecked under it.
  • At the very least, When one child is checked, its parent should be checked.
  • When no child is checked, its parents should not be checked.

I have done this work to some extent. But I look forward to your help in completing this.

This is how I tried it using Jquery.

$('#myTable').on( "change", "label > input[type=checkbox]", function(e) {
  var checkboxes = $(this).closest('tr').find("input[type=checkbox]");
  if ($(this).hasClass("parent")) { 
    if ($(this).prop("checked")) {
      checkboxes.prop("checked", true);
    }
  }
});

Is there a way to delete this tabs after creating them using cloneNode() in vanilla javascript?

I am trying to create a function in my vanilla JavaScript to delete tabs created by using cloneNode(true). Below is what i have tried but its not just working.

I created a form with class named secondSectionEmail; at the click of the button (+), the form is duplicated using cloneNode(). Each form is carrying a (x) button which is supposed to delete a particular tab. How do I achieve this please?

<form class="secondSectionEmail"> 
 <button id="closeBtn">x</button>
 <input type="email" id="recipient" placeholder="Enter Recipient Email">
 <input type="text" placeholder="Subject"><br>
  <textarea type="text" placeholder="Enter Message"></textarea>
    <div class="upload">
        <input type="file" multiple>
        <button>Send Mail</button>
    </div>
 </form>
<br>
<br>
<button type="submit" id="arrow">+</button>

<script>
//script to add new tab
let addbutton = document.getElementById("arrow");
var i = 0;

addbutton.addEventListener("click", function (e) {
  e.preventDefault();
    let boxes = document.querySelector(".secondSectionEmail");
    let closeC = document.getElementById('closeBtn');
    var clone = boxes.cloneNode(true);
  
    i++;
    clone.className=`secondSectionEmail${i}`;
    clone.classList.add(`mydiv`);
    closeC.classList.add(`timzy${i}`);
    boxes.after(clone);
})



//Script to delete tab
let deleteButton = document.querySelector(`.container`)

deleteButton.addEventListener("click", function (event) {
event.preventDefault()
  var del = event.target.parentElement.className;
  let newDel = document.getElementsByClassName(`${del}`);
  let newDelete = Array.from(newDel)
  console.log(newDelete)
})
</script>