Shopify slick carousel with dynamic image blocks

I am trying to implement a slick carousel in the home page. The slides for the carousel are added as blocks in the slider section. I have already added the required css, js and jquery cdn in my theme.liquid file. In the customize option for shopify, I can now add dynamic images for the slideshow but the carousel or the images are not showing up on the website.

Here’s my theme.liquid file:

<!doctype html>
<html>
<head>

  <title>{{ page_title }}</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="description" content="{{ page_description | escape }}">
  <link rel="canonical" href="{{ canonical_url }}">
  <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
  
  <!--css file-->
  <link rel="stylesheet" href="{{ 'custom.css' | asset_url }}" type="text/css" media="print" onload="this.media='all';onLoadStylesheet()">
  
  <!--slick css?-->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.css" integrity="sha512-wR4oNhLBHf7smjy0K4oqzdWumd+r5/+6QO/vDda76MW5iug4PT7v86FoEkySIJft3XA0Ae6axhIvHrqwm793Nw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

  {{ content_for_header }}
</head>

<body>
  {% section 'header' %}

  <main role="main">
    {{ content_for_layout }}
  </main>

  <!--slick jquery and js-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js" integrity="sha512-XtmMtDEcNz2j7ekrtHvOVR4iwwaD6o/FUJe6+Zq+HgcCsk3kj4uSQQR8weQ2QVj1o0Pk6PwYLohm206ZzNfubg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html>

my slider.liquid file:

<div class="slider-container">
    <div class="image-container">
        {% for slide in settings.blocks %}
            <div class="image-title">
                {{ slide.slide_title }}
            </div>

            <div class="slider-image">
                <img src="{{ slide.slide_img | img_url: 'grande' }}">
            </div>

        {% endfor %}
    </div>

    <div class="slider-next">Next</div>
    <div class="slider-prev">Prev</div>
</div>

<script>
    $('.slider-container').slick({
      dots: false,
      infinite: true,
      speed: 300,
      slidesToShow: 5,
      slidesToScroll: 5,
      nextArrow:$('.slider-next'),
      prevArrow:$('.slider-prev'),
      responsive: [
        {
          breakpoint: 1024,
          settings: {
            slidesToShow: 3,
            slidesToScroll: 3,
            infinite: true,
            dots: false
  
          }
        },
        {
          breakpoint: 600,
          settings: {
            slidesToShow: 2,
            slidesToScroll: 2
          }
        },
        {
          breakpoint: 480,
          settings: {
            slidesToShow: 1,
            slidesToScroll: 1
          }
        }
      ]
    });
  </script>

{% schema %}
{
  "name": "Slideshow",
  "tag": "section",
  "class": "slideshow",
  "max_blocks": 5,
  "settings": [
    {
      "type": "text",
      "id": "title",
      "label": "Slideshow"
    }
  ],
  "blocks": [
     {
       "name": "Slide",
       "type": "slide",
       "settings": [
         {
           "type": "image_picker",
           "id": "slide_image",
           "label": "Image"
         }, 
         {
            "type": "text",
            "id":"slide_title",
            "label":"Title"
         }
       ]
     }
   ],
  "presets": [
     {
       "name": "Slideshow",
       "settings": {
          "title": "Slideshow"
        },
       "blocks": [
         {
           "type": "slide"
         },
         {
           "type": "slide"
         }
       ]
     }
   ]
}
{% endschema %}

my index.liquid file:


{{ content_for_index }}

{% section 'slider' %}

Value undefined for React-Query useQuery() hook when used as a function

This is an extremely perplexing issue. The code below gives this error:

TypeError: Cannot read properties of undefined (reading 'map')

When console.log() is used to look at res.data it is fine, it has data. res.data.products is undefined, therefore blowing up the .map(). It just doesn’t make sense why this doesn’t work. Starting to think there is a bug in the react-query library

export default function ProductList() {
  const { data: products, isLoading } = useQuery('Products', () => 
    axios('/api/products').then((res) => res.data.products)
  );

  if (isLoading) return <LoadingSpinner />

  return products.map((product) => (
    <ProductItem key={product.id} product={product} /> 
  ));
}

How to remove each note on dblclick and also remove from the array with filter method

I need help to remove each note on dblclick and also remove from the notes array with filter method. We should use unique id with Math.random()

Here is my code

let notes = [];
const container = document.querySelector('.flex-cont')
const inputNote = document.getElementById('noteInput')
const addButton = document.getElementById('addNote')
let noteElement;


class Note {
  constructor(description, id) {
    this.description = description
    this.id = id
  }
}

addButton.addEventListener('click', postNote)

function postNote() {
  let note = inputNote.value
  let newNote = new Note(note, Math.random())
  noteElement = document.createElement('div')
  noteElement.classList.add('paper', 'pink')
  noteElement.setAttribute('id', this.id)
  let noteText = document.createElement('p')
  noteText.textContent = note
  noteElement.append(noteText)
  let tape = document.createElement('div')
  tape.classList.add('tape-section')
  noteElement.append(tape)
  noteElement.addEventListener('dblclick', () => {
    // notes.filter(id => this.id != id )
    // if (noteElement.id === this.id) {
      const doDelete = confirm('Are you sure ?');
      if (doDelete) {
        noteElement.remove()
      }
    // }
    
  })
  container.appendChild(noteElement)
  notes.push(newNote) 
  inputNote.value = '';
}

console.log(notes)

HTML and CSS are here

http://jsfiddle.net/30tjop4d/

Filtering a bscscan object with multiple transactions to separate into two objects matching key:values

Using BSCScan’s Accounts API , I am returning a list of transactions between a Contract address and a User address.

The response contains transaction details that are transfers from either:

  • A) The contract to the user address (from buys)
  • B) The user address to the contract (from sells)

In the BSCScan response, we can see information such as the tx hash/blockNumber/ value and who it was from to etc.
What I’m looking for is to sum all the value: entries separately for A and B where

  • A) the from: key value is equal to the contract address and the to key value matches the user address
  • B) the from: key value is equal to the user address and the to key value matches the contract address

My BSCScan fetch call and function is

useEffect(() => {
    fetch("https://api.bscscan.com/api?module=account&action=tokentx&contractaddress=0x9cdadB8982f772B64D852577CD85672D87b27974&address=0x541b79b200B40D37F91663e40Ca0B05512d0EB05&page=1&offset=5&startblock=0&endblock=999999999&sort=asc&apikey=xxxxxxxxxxxxxx")
      .then(resp => resp.json())
      .then(resp => {
        console.log(resp); 
        // console.log(resp.result); 
        // console.log(resp.result[0]); 
        // console.log(resp.result[0].from); 
        const data = resp.result
        let from = ['0x9cdadB8982f772B64D852577CD85672D87b27974'];   //im trying to filter out only the results with FROM: this address

var result2 = data.filter(function(e) {
  return from.indexOf(e.from)
})

console.log(result2)
      
        
      })
  }, []);

Here’s the object I have, note there’s five transactions here but in reality there would be many more to iterate through.

{
    "status": "1",
    "message": "OK",
    "result": [
        {
            "blockNumber": "17805652",
            "timeStamp": "1652563670",
            "hash": "0x861e3581867499baf07e7eb6e376d1d8adf2c8ee204065b670f7abbdb4c1c5e4",
            "nonce": "588",
            "blockHash": "0xf88c6a5891fc3f5dc9f9abbd0d929c98144416153435d6643c74611d7dd74c56",
            "from": "0x0470c451fb5eceffddca244e5ead99c049b0e75d",
            "contractAddress": "0x9cdadb8982f772b64d852577cd85672d87b27974",
            "to": "0x541b79b200b40d37f91663e40ca0b05512d0eb05",
            "value": "1581034057919837469495682682",
            "tokenName": "FlokiLuna",
            "tokenSymbol": "FLUNA",
            "tokenDecimal": "18",
            "transactionIndex": "26",
            "gas": "566239",
            "gasPrice": "5000000000",
            "gasUsed": "363220",
            "cumulativeGasUsed": "2601281",
            "input": "deprecated",
            "confirmations": "112826"
        },
        {
            "blockNumber": "17807282",
            "timeStamp": "1652568601",
            "hash": "0x4767c35b9cb494a31c141639ca7c7507c488a7b0a837ffcad5f5e34b601b03c7",
            "nonce": "591",
            "blockHash": "0xb886991a4fd64a78b5ae5132eecde7fa4b1f5a9a5965a3efcb2ef6af0be85b97",
            "from": "0x541b79b200b40d37f91663e40ca0b05512d0eb05",
            "contractAddress": "0x9cdadb8982f772b64d852577cd85672d87b27974",
            "to": "0x9cdadb8982f772b64d852577cd85672d87b27974",
            "value": "50000000000000000",
            "tokenName": "FlokiLuna",
            "tokenSymbol": "FLUNA",
            "tokenDecimal": "18",
            "transactionIndex": "85",
            "gas": "1757466",
            "gasPrice": "5000000000",
            "gasUsed": "982256",
            "cumulativeGasUsed": "10797282",
            "input": "deprecated",
            "confirmations": "111196"
        },
        {
            "blockNumber": "17807282",
            "timeStamp": "1652568601",
            "hash": "0x4767c35b9cb494a31c141639ca7c7507c488a7b0a837ffcad5f5e34b601b03c7",
            "nonce": "591",
            "blockHash": "0xb886991a4fd64a78b5ae5132eecde7fa4b1f5a9a5965a3efcb2ef6af0be85b97",
            "from": "0x541b79b200b40d37f91663e40ca0b05512d0eb05",
            "contractAddress": "0x9cdadb8982f772b64d852577cd85672d87b27974",
            "to": "0x0470c451fb5eceffddca244e5ead99c049b0e75d",
            "value": "950000000000000000",
            "tokenName": "FlokiLuna",
            "tokenSymbol": "FLUNA",
            "tokenDecimal": "18",
            "transactionIndex": "85",
            "gas": "1757466",
            "gasPrice": "5000000000",
            "gasUsed": "982256",
            "cumulativeGasUsed": "10797282",
            "input": "deprecated",
            "confirmations": "111196"
        },
        {
            "blockNumber": "17808244",
            "timeStamp": "1652571500",
            "hash": "0xadcc3c7ea29766a18f0da1f6bac4ed12f06ad3d0748b66851dbb52d59e0d68f4",
            "nonce": "592",
            "blockHash": "0xa58678c9537fea84d153d27c54998f573d60ec69b8f62a54b4426469c1fd4d1f",
            "from": "0x541b79b200b40d37f91663e40ca0b05512d0eb05",
            "contractAddress": "0x9cdadb8982f772b64d852577cd85672d87b27974",
            "to": "0x9cdadb8982f772b64d852577cd85672d87b27974",
            "value": "35783452330550414065088721",
            "tokenName": "FlokiLuna",
            "tokenSymbol": "FLUNA",
            "tokenDecimal": "18",
            "transactionIndex": "83",
            "gas": "1757569",
            "gasPrice": "5000000000",
            "gasUsed": "970241",
            "cumulativeGasUsed": "10820065",
            "input": "deprecated",
            "confirmations": "110234"
        },
        {
            "blockNumber": "17808244",
            "timeStamp": "1652571500",
            "hash": "0xadcc3c7ea29766a18f0da1f6bac4ed12f06ad3d0748b66851dbb52d59e0d68f4",
            "nonce": "592",
            "blockHash": "0xa58678c9537fea84d153d27c54998f573d60ec69b8f62a54b4426469c1fd4d1f",
            "from": "0x541b79b200b40d37f91663e40ca0b05512d0eb05",
            "contractAddress": "0x9cdadb8982f772b64d852577cd85672d87b27974",
            "to": "0x0470c451fb5eceffddca244e5ead99c049b0e75d",
            "value": "679885594280457867236685711",
            "tokenName": "FlokiLuna",
            "tokenSymbol": "FLUNA",
            "tokenDecimal": "18",
            "transactionIndex": "83",
            "gas": "1757569",
            "gasPrice": "5000000000",
            "gasUsed": "970241",
            "cumulativeGasUsed": "10820065",
            "input": "deprecated",
            "confirmations": "110234"
        }
    ]
}

Here’s an image showing the goal I want to achieve

Save a changing variable in javascript

In my code I want to save an object that changes during the execution in an array inorder to use it after the execution of the function,so I tried to create a copy of it using this approach:

let copy=[...original]//original is the variable that changes during the execution
when I used this approach I noticed that the content of the copied array is the same as the last value of the original array.
Now I need a method that can keep all the states of the original array in one variable.

How to check for username and email in nestjs validation. The async function awaits for findbyusername and then never reaches the else condition

How to check for username and email in nestjs validation. The async function awaits for findbyusername and then never reaches the else condition.

I am trying to create one validation method to check if entered value in userNameorEmail field is username or email but looks like the function never reaches to the else statement. It just throws the error when I do then and catch. How can I make it work. Thanks for your help in advance.

  async validateUser(userNameorEmail: string, pass: string): Promise<any> {

    const resultByUsername = await this.usersService.findbyUsername(userNameorEmail);

    if (resultByUsername && resultByUsername.password === pass) {
      const { password, ...result } = resultByUsername;
      return result;

    } else {
      const resultByEmail = await this.usersService.findbyEmail(userNameorEmail);

      if (resultByEmail && resultByEmail.password === pass) {
        const { password, ...result } = resultByEmail;
        return result;

      }
    }

Tailwind – Autoprefixer already exists

when installing tailwind I get the following error:

admin@admin-VirtualBox:~/Desktop/Code/react_app/client$ npm install -D tailwindcss postcss autoprefixer
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/autoprefixer
npm ERR!   autoprefixer@"^9.6.1" from [email protected]
npm ERR!   node_modules/postcss-preset-env
npm ERR!     postcss-preset-env@"6.7.0" from [email protected]
npm ERR!     node_modules/react-scripts
npm ERR!       react-scripts@"3.2.0" from the root project
npm ERR!   dev autoprefixer@"*" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! dev autoprefixer@"*" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/postcss
npm ERR!   peer postcss@"^8.1.0" from [email protected]
npm ERR!   node_modules/autoprefixer
npm ERR!     dev autoprefixer@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/admin/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/admin/.npm/_logs/2022-05-17T19_33_57_115Z-debug-0.log

I am using the following package.json file:

{
  "name": "react-app",
  "version": "1.0",
  "private": true,
  "dependencies": {
    "babel-eslint": "10.0.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router": "^6.3.0",
    "react-scripts": "3.2.0",
    "web3": "^1.6.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

This is the fill log:

0 verbose cli [
0 verbose cli   '/usr/local/bin/node',
0 verbose cli   '/usr/local/bin/npm',
0 verbose cli   'install',
0 verbose cli   '-D',
0 verbose cli   'tailwindcss',
0 verbose cli   'postcss',
0 verbose cli   'autoprefixer'
0 verbose cli ]
1 info using [email protected]
2 info using [email protected]
3 timing npm:load:whichnode Completed in 0ms
4 timing config:load:defaults Completed in 1ms
5 timing config:load:file:/usr/local/lib/node_modules/npm/npmrc Completed in 8ms
6 timing config:load:builtin Completed in 8ms
7 timing config:load:cli Completed in 1ms
8 timing config:load:env Completed in 0ms
9 timing config:load:file:/home/admin/Desktop/Code/react_app/client/.npmrc Completed in 0ms
10 timing config:load:project Completed in 2ms
11 timing config:load:file:/home/admin/.npmrc Completed in 1ms
12 timing config:load:user Completed in 1ms
13 timing config:load:file:/usr/local/etc/npmrc Completed in 0ms
14 timing config:load:global Completed in 0ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:credentials Completed in 0ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 14ms
19 timing npm:load:configload Completed in 14ms
20 timing npm:load:setTitle Completed in 0ms
21 timing config:load:flatten Completed in 2ms
22 timing npm:load:display Completed in 3ms
23 verbose logfile /home/admin/.npm/_logs/2022-05-17T19_33_57_115Z-debug-0.log
24 timing npm:load:logFile Completed in 2ms
25 timing npm:load:timers Completed in 0ms
26 timing npm:load:configScope Completed in 0ms
27 timing npm:load Completed in 19ms
28 timing arborist:ctor Completed in 1ms
29 silly logfile start cleaning logs, removing 1 files
30 timing idealTree:init Completed in 769ms
31 timing idealTree:userRequests Completed in 1ms
32 silly idealTree buildDeps
33 silly fetch manifest tailwindcss@*
34 timing arborist:ctor Completed in 0ms
35 http fetch GET 200 https://registry.npmjs.org/tailwindcss 796ms (cache hit)
36 silly fetch manifest postcss@*
37 http fetch GET 200 https://registry.npmjs.org/postcss 8ms (cache hit)
38 silly fetch manifest autoprefixer@*
39 http fetch GET 200 https://registry.npmjs.org/autoprefixer 5ms (cache hit)
40 timing idealTree Completed in 1610ms
41 timing command:install Completed in 1615ms
42 verbose stack Error: could not resolve
42 verbose stack     at PlaceDep.failPeerConflict (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/place-dep.js:546:25)
42 verbose stack     at PlaceDep.place (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/place-dep.js:197:21)
42 verbose stack     at new PlaceDep (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/place-dep.js:71:10)
42 verbose stack     at /usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:964:31
42 verbose stack     at Array.map (<anonymous>)
42 verbose stack     at Arborist.[buildDepStep] (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:964:8)
42 verbose stack     at async Arborist.buildIdealTree (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:216:7)
42 verbose stack     at async Promise.all (index 1)
42 verbose stack     at async Arborist.reify (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:153:5)
42 verbose stack     at async Install.exec (/usr/local/lib/node_modules/npm/lib/commands/install.js:159:5)
43 verbose cwd /home/admin/Desktop/Code/react_app/client
44 verbose Linux 5.13.0-40-generic
45 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-D" "tailwindcss" "postcss" "autoprefixer"
46 verbose node v16.15.0
47 verbose npm  v8.5.5
48 error code ERESOLVE
49 error ERESOLVE could not resolve
50 error
51 error While resolving: [1mreact-app[22m@[1m1.0[22m
51 error Found: [1mautoprefixer[22m@[1m9.7.1[22m[2m[22m
51 error [2mnode_modules/autoprefixer[22m
51 error   [1mautoprefixer[22m@"[1m^9.6.1[22m" from [1mpostcss-preset-env[22m@[1m6.7.0[22m[2m[22m
51 error   [2mnode_modules/postcss-preset-env[22m
51 error     [1mpostcss-preset-env[22m@"[1m6.7.0[22m" from [1mreact-scripts[22m@[1m3.2.0[22m[2m[22m
51 error     [2mnode_modules/react-scripts[22m
51 error       [1mreact-scripts[22m@"[1m3.2.0[22m" from the root project
51 error   [33mdev[39m [1mautoprefixer[22m@"[1m*[22m" from the root project
51 error
51 error Could not resolve dependency:
51 error [33mdev[39m [1mautoprefixer[22m@"[1m*[22m" from the root project
51 error
51 error Conflicting peer dependency: [1mpostcss[22m@[1m8.4.13[22m[2m[22m
51 error [2mnode_modules/postcss[22m
51 error   [35mpeer[39m [1mpostcss[22m@"[1m^8.1.0[22m" from [1mautoprefixer[22m@[1m10.4.7[22m[2m[22m
51 error   [2mnode_modules/autoprefixer[22m
51 error     [33mdev[39m [1mautoprefixer[22m@"[1m*[22m" from the root project
51 error
51 error Fix the upstream dependency conflict, or retry
51 error this command with --force, or --legacy-peer-deps
51 error to accept an incorrect (and potentially broken) dependency resolution.
51 error
51 error See /home/admin/.npm/eresolve-report.txt for a full report.
52 verbose exit 1
53 timing npm Completed in 1755ms
54 verbose unfinished npm timer reify 1652816037244
55 verbose unfinished npm timer reify:loadTrees 1652816037246
56 verbose unfinished npm timer idealTree:buildDeps 1652816038016
57 verbose unfinished npm timer idealTree:#root 1652816038016
58 verbose code 1
59 error A complete log of this run can be found in:
59 error     /home/admin/.npm/_logs/2022-05-17T19_33_57_115Z-debug-0.log

Any suggestions what I am doing wrong?

I appreciate your replies!

TypeError: Assignment to constant variable. prefix d.js v13

module.exports = (client, message) => {

    

    const Discord = module.require('discord.js')
    const db = require('quick.db')

    const embedzi = new Discord.MessageEmbed()
    .setTitle('Wzmianka!')
    .setDescription('Wykryto oznaczenie bota! n Mój prefix to `c!` n Spis komend znajdziesz pod `c!help`')
    .setColor('GREEN')
    if (message.mentions.has(client.user)) {
        message.channel.send({ embeds: [embedzi] });

    }


        const default_prefix = 'c!'
      const  prefix = db.get(`prefix_${message.guild.id}`)
    if(prefix === null) prefix === default_prefix;
 
    if (!message.content.startsWith(prefix)) return;
     

    const messageArray = message.content.split(" ");
    const cmd = messageArray[0]
    const args = messageArray.slice(1);

    const commandFile = client.commands.get(cmd.slice(prefix.length).toString().toLowerCase()) || client.commands.get(client.aliases.get(cmd.slice(prefix.length).toString().toLowerCase())); 
    if (commandFile) {
        commandFile.run(client, message, args, prefix);
   


    }


}

Uncaught (in promise) TypeError: Converting circular structure to JSON In Client side when posting to backend

const handleAddItem = event =>{
    event.preventDefault()
    const item = {
        name: event.target.name.value,
        description: event.target.name.value,
        img: event.target.img,
        category: event.target.category.value,
        email: user.email,
        quantity: event.target.quantity.value,
        price: event.target.price.value,
        suppName: event.target.supplierName.value
    }
    console.log(item);
    axios.post('the Url', item)
    .then(response => {
        console.log(response)
        const {data} = response;
        if(data.insertedId){
            alert('User Added Successfully')
        event.target.reset();
        }
    })

This is my code and the qrror is shown when I try to post my array. Don’t understand why happening. my backend is totally good.
the title of the error is

Javascript let attempt1 = false not working [closed]

I was trying to make a website that ask a questions about a person(Chris Metzen) and if you attempt it once, you can not try again and finally display the score(not coded yet) but when I try the code, it will display that you already made an attempt when this was my first time after closing and opening it back. I think I messed something up with my code and please tell me why my code is not working (Btw I brought entire code but I don’t think that you need to read all of them)

let score = 0;
let attempt1 = false;
let attempt2 = false;
let attempt3 = false;
let attempt4 = false;

function quiz1() {
    if (attempt1 = true) {
        alert("Sorry! you have already attempted in this quiz.");
    } else {
        let response = window.prompt("What is Chris Metzen's birthday?");
        let answer = "november 22, 1973"
        let alternativeAnswer = "november 22"
        if (response.toLowerCase() == answer || response.toLowerCase() == alternativeAnswer) {
            document.getElementById("firstQuiz").innerHTML = "Correct!";
            score++;
        } else {
            document.getElementById("firstQuiz").innerHTML = "False";
        }
        attempt1 = true;
    }
}

function quiz2() {
    if (attempt2 = true) {
        alert("Sorry! you have already attempted in this quiz.");
    } else {
        let response = window.prompt("For how much years was Chris metzen active?");
        let answer = "23 years"
        let alternativeAnswer = "23"
        if (response.toLowerCase == answer || response == alternativeAnswer) {
            document.getElementById("secondQuiz").innerHTML = "Correct!"
            scroe++;
        } else {
            document.getElementById("secondQuiz").innerHTML = "False"
        }
        attempt2 = true;
    }
    
}

function quiz3() {
    let response = window.prompt("Chris Metzen's first game that he contributed was ___.");
    let answer = "justice league task force"
    if (response.toLowerCase() == answer) {
        document.getElementById("thirdQuiz").innerHTML = "Correct!"
    } else {
        document.getElementById("thirdQuiz").innerHTML = "False"
    }
}


function quiz4() {
    let response = window.prompt("In 1998, he took the role of lead designer on the science fiction strategy game ___.");
    let answer = "starcraft"
    let alternativeAnswer = "starcraft series"
    if (response.toLowerCase() == answer || response.toLowerCase() == alternativeAnswer) {
        document.getElementById("fourthQuiz").innerHTML = "Correct!"
    } else {
        document.getElementById("fourthQuiz").innerHTML = "False"
    }
}

Take a specific value of a map array in reactJS

i am working with a REST API that provides data for different countries. I have a search box and when i am typing letters under the box appeared different countries that matches with the search. Each country that appears has a button beside and when you click that button some information about this country appears. I have two different components, the first component showing the countries that matches the search and the second component showing the information from the selected country.

The code of the first component:

import {useState} from 'react'
import TheCountry from './TheCountry'

const TheSearchCountry= ({countrie}) => {

 const [buttonClicked, setButtonClicked] = useState(true)

 return (
    buttonClicked ?
        countrie.map(country => (
            <p key={country.name}>
                {country.name}
                <button onClick={() => {setButtonClicked(false)}}>show</button>
            </p>
        ))
    : <TheCountry countries={countrie} />
  )
}

export default TheSearchCountry

The second component called

<TheCountry/>

When the user clicks the show button i want to call the component

<TheCountry/>

and show in the screen the details about this particular country. But something like this did not happen, i screen all the data for all the countries that matches the search query. I did not find a correct way to call my component and isolate the country that trigger the button. Can anyone help ?

Change a button onclick href based on multiple IDs

I have an order summary. The order summary is a collection of 5 different HTML IDs based on user selection. I’m trying to get the “checkout button” to link to different URL’s based on the ID configurations. For example, if the user selects “BRAZIL”, “2 BAGS”, “WHOLE BEAN”, “EVERY 4 WEEKS”, “ALL ROAST TYPES” the checkout button would take them to a specific URL and so on. I’m assuming a for loop and if… else statement would do the trick but I can’t seem to figure it out. I feel like I’m close but maybe I’m way off. Any help would be appreciated from the JavaScript masters of Stack Overflow 🙂

// CHECKOUT BUTTON CONDITIONALS
                        function checkoutButton(){
                                let checkoutBtnClick = document.querySelectorAll("#change-coffee, #change-bag, #change-grind-type, #change-delivery, #change-roast-type").innerHTML;
                                if (checkoutBtnClick === "BRAZIL", "2 BAGS", "WHOLE BEAN", "EVERY 4 WEEKS", "ALL ROAST TYPES") {
                                    document.getElementById("box-summary-checkout-button").setAttribute('onclick', 'window.location.href="https://www.google.com/"');                    
                                } else if (checkoutBtnClick === "BRAZIL", "2 BAGS", "GROUND", "EVERY 4 WEEKS", "ALL ROAST TYPES") {
                                    document.getElementById("box-summary-checkout-button").setAttribute('onclick', 'window.location.href="https://www.facebook.com/"');
                                }
                            }
                        
/* ORDER SUMMARY */
.container-summary {
    display: flex;
    border: 3px solid none;
    justify-content: center;
    margin-bottom: 50px;
    font-family: 'lato', sans-serif;
}

.box-summary {
    height: 20.5rem;
    width: 30rem;
    background: #eee;
    border-radius: 6px;
}

.box-summary-title {
    display: flex;
    justify-content: center;
    font-size: 20px;
    font-weight: 600;
    letter-spacing: .03rem;
    margin-top: 25px;
    color: #433d3d;
    line-height: .95em;
}

.box-summary-block {
    display: flex;
    justify-content: space-around;
    margin: 1rem 3rem;
    font-size: 13px;
    font-weight: 600;
    letter-spacing: .03rem;
    line-height: 1.9em;
    color: #393939;
}

.box-summary-block-coffee {
    display: flex;
    justify-content: center;
    margin: 1rem 4rem;
    font-size: 13px;
    font-weight: 600;
    letter-spacing: .03rem;
    line-height: 1.9em;
    color: #393939;
}

.box-summary-option-coffee {
    margin-left: .75rem;
}

.box-summary-block-right {
    text-align: end;
}

.box-summary-category2-left, 
.box-summary-category2-right {
    margin-top: .6em;
}

.box-summary-option-bags, 
.box-summary-option-grind, 
.box-summary-option-delivery,
.box-summary-option-roast,
.box-summary-option-coffee {
    color: #3e718a;
} 

.box-summary-shipment-plus-price {
    display: flex;
    justify-content: space-evenly;
    margin-left: 60px;
    margin-right: 60px;
    margin-bottom: 10px;
    margin-top: 20px;
    font-size: 15px;
    font-weight: 600;
    letter-spacing: .03rem;
    line-height: .95em;
    color: #433d3d;
}

.box-summary-order-button-container {
    display: flex;
    justify-content: center;
}

.box-summary-order-button {
    padding: 15px 30px 15px 30px;
    font-size: 15px
}
<!--ORDER SUMMARY CONTAINER-->
    <div class="container-summary">
        <div class="box-summary">
            <div class="box-summary-title">
                ORDER SUMMARY
            </div>
            <div class="box-summary-block-coffee">
                COFFEE SELECTION: <span class="box-summary-option-coffee" id="change-coffee">BRAZIL</span>
            </div>

            <div class="box-summary-block">
                <div class="box-summary-block-left">
                    <div class="box-summary-category1-left">
                        # OF BAGS
                    </div>
                    <div class="box-summary-option-bags" id="change-bag">
                        2 BAGS
                    </div>
                    <div class="box-summary-category2-left">
                        GRIND TYPE
                    </div>
                    <div class="box-summary-option-grind" id="change-grind-type">
                        WHOLE BEAN
                    </div>
                </div>

                <div class="box-summary-block-right">
                    <div class="box-summary-category1-right">
                        DELIVERY
                    </div>
                    <div class="box-summary-option-delivery" id="change-delivery">
                        EVERY 4 WEEKS
                    </div>
                    <div class="box-summary-category2-right">
                        ROAST TYPE
                    </div>
                    <div class="box-summary-option-roast" id="change-roast-type">
                        ALL ROAST TYPES
                    </div>
                </div>

            </div>

            <div class="box-summary-order-summary">
                <div class="box-summary-shipment-plus-price">
                    <span class="box-summary-price-per-shipment">
                        PRICE PER SHIPMENT:
                    </span>
                    <span class="box-summary-order-price" id="box-summary-total-price">
                        $90
                    </span>
                </div>
                <div class="box-summary-order-button-container">
                    <button class="box-summary-order-button" id="box-summary-checkout-button" onclick="checkoutButton()">
                        CONTINUE TO CHECKOUT
                    </button>

CORS Policy Blocked Error with JSON, but Switching Header Type Fixes Error?

I made this simple input form that displays data when I add info to them.

So I followed this tutorial and they made this header with application/json for rendering json data through input fields.

                   let url = 'http://localhost:3000/';
                    let h = new Headers()

                    h.append('Content-type', 'application/json')
                    let req = new Request(url, {
                        headers: h,
                        body: json,
                        method: 'POST'
                    })

However, reading the MDN docs, it shows that there’s only 3 content types and I don’t understand which one to use when trying to display JSON data.

According to the docs it says

 It also needs to have a MIME type of its parsed value (ignoring parameters) 
 of either application/x-www-form-urlencoded, multipart/form-data, or text/plain.

So if I just switch my code to this, the error goes away, but I don’t know if this is the correct method.

h.append('Content-type', 'multipart/form-data')
let req = new Request(url, {
    headers: h,
    body: json,
    method: 'POST'
})

In the tutorial, he said it only shows the error because he is using a different port number and not addressing it in the server?

https://www.youtube.com/watch?v=GWJhE7Licjs timestamp 10:40

However, everything before that it worked completely fine until he added the json data option?

CodeMirror: load default yaml file

I’m currently trying to get CodeMirror to load a yaml file for me.

Backend (slimmed down for stackoverflow):

    import fs from "fs-extra";
    import yaml from "js-yaml";

    const conf = yaml.load(fs.readFileSync('./config.yml', 'utf-8'));
        
    router.get('/', (req, res) => {
        res.render('settings.ejs', {
            page_name: 'settings',
            yaml_config: JSON.stringify(conf)
        });
    
        console.log(JSON.stringify(conf));
    });

Frontend:

    <div id="editor"></div>
    <script>
        const editor = CodeMirror(document.getElementById('editor'), {
            mode: 'yaml',
            styleActiveLine: true,
            lineNumbers: true,
            foldGutter: true,
            gutters: [
                "CodeMirror-linenumbers", "CodeMirror-foldgutter"
            ],
            theme: 'material',
            value: "<%= yaml_config%>"
        });
    </script>

Without the JSON.stringify will just load "[Object] [object], the console output of console.log(JSON.stringify(conf)); is: {"port":"3000","maxCPU":"30","maxMem":"4","maxDisk":"2"}, but whats being written to CodeMirror is {&#34;port&#34;:&#34;3000&#34;,&#34;maxCPU&#34;:&#34;30&#34;,&#34;maxMem&#34;:&#34;4&#34;,&#34;maxDisk&#34;:&#34;2&#34;}

Any solutions to my problem?