how to change value of object in array using setState with React

hello everyone good evening,

I have array of object set in state and i would like to change some object in the array.

so here is my array us you can see:

    const [CategoriesArr, setCategoriesArr] = useState([
    {
        image: anime,
        nameByCategories: "Aninate",
        allCard: [
            silverCard, blackCard
        ],
    },
    {
        image: vacation,
        nameByCategories: "Vacation",
        allCard: [
            blackCard, silverCard
        ],
    },])

i tried to change the allCard to: allCard:blackCard, blackCard

with this way:

setCategoriesArr([
{
    ...CategoriesArr[0],
    allCard: [
        silverCard, silverCard
    ]
}])

the problem is after the setState i get new array with changes that i want and also the last array so it means like this

  {
        image: anime,
        nameByCategories: "Aninate",
        allCard: [
            blackCard, blackCard
        ],
    },
    {
        image: vacation,
        nameByCategories: "Aninate",
        allCard: [
            silverCard, blackCard
        ],
    },
  {
        image: anime,
        nameByCategories: "vacations",
        allCard: [
            blackCard, silverCard
        ],
    },

i would like to understand i can i get new array exact like that:

    const [CategoriesArr, setCategoriesArr] = useState([
{
    image: anime,
    nameByCategories: "Aninate",
    allCard: [
        silverCard, blackCard
    ],
},
{
    image: vacation,
    nameByCategories: "Vacation",
    allCard: [
        blackCard, blackCard
    ],
},])

pleas.

i hope you guys going to help me 🙂

items.map is not a function react

I’m having a problem with fetching data from my api, and displaying it on a web page. I am getting this error : “items.map is not a function”. Im not sure whether this is a problem with this code or maybe my code for my get request in the api, I’ll post both codes just in case.

I’ll paste my code below without the link to my api.
Thanks,

import React from "react";

class App extends React.Component {


  constructor(props) {

    super(props);

    this.state = {
        items: [],
        isLoaded: false
    }

}

componentDidMount() {

  fetch(" api link ")
      .then(res => res.json())
      .then(json => {
        this.setState({ isLoaded: true, items: json });
      }).catch((err) => {
          console.log(err);
      });

}


render() {

  const { isLoaded, items } = this.state;

  if (!isLoaded)
      return <div>Loading...</div>;

  return (
      <div className="App">
          <ul>
              {items.map(item => (
                  <li key={item.oid}>
                      Name: {item.rows.productName} | Condition: {item.rows.productCondition}
                  </li>
              ))}
          </ul>
      </div>
  );

}

}

export default App;

Api code:

async function getComments(req) {
   let status = 500, data = null;
   try {

         const sql = 'SELECT * FROM products';
         const rows = await db.query(sql);

         if (rows) {
            status = 200;
            data = {
                rows,

            };
         } else {
            status = 204;
         }
     
   } catch (e) {
      console.error(e);
   }
   return { status, data };
}


app.get('/demo/api_project', async (req, res) => {
   const { status, data } = await getComments(req);
   res.status(status);
   if (data) res.json(data);
   else res.end();
})

Javascript NodeJS – Can we make a local function variable becomes a global variables inside of class? [duplicate]

I’ve been trying to make these code works what I expected, but it doesn’t really works what I expected

import fetch from 'node-fetch';
const BASE_URL = 'https://estra-api.herokuapp.com/';

let EstraLoader = class Estra {
    loadAPI() {
        var data = '';
        fetch(BASE_URL)
        .then(function (response) {
        return response.json();
    })
        .then(function (myJson) {
        data = myJson;
        return data["Version"];
    });
}};

let EstraJS = new EstraLoader();
console.log(EstraJS.loadAPI());

The output always undefined, is there anything I can change from this codes that I made?

All I did want was the return data["Version"]; gives output by using console.log(EstraJS.loadAPI());

Render component after keyboard closes or listen to keyboard close event in react app in cordova android

I am migrating a ‘work-in-progress’ react.js application to an android app using cordova.
all seems to work fine except for a component that doesnt render itself peoperly when the keyboard closes, the component generally looks like this.
enter image description here

Now when you click on an input and close it the view re renders just fine:
enter image description here

But once you fill it and close the keyboard the component doesnt re render itself:
enter image description here
enter image description here

the component just gets stuck like that, the easy solution would obviously be to “force render” by setting the state again, the issue is that I cant seem to find a way to listen to keyboard changes on this react-cordova app, also why would the component re render itself when the form is empty but not when its filled?

I dont’ understand why I have a message error with my ROUTE POST API?

I am a project, and my goal is to create an API. During authentication a user can create a sauce with different fields. I am working with mongoDB. When I submit the form, the image saves well in my backend, but nothing on the page and nothing on collection (mongodb atlas).

This is what I have to respect :
request body :{ sauce: String,image: File }
type of response :{ message: String }Verb
And which is recorded from the frontend. I just have to take care of the backend and not touch anything on the frontend side.

I have successfully connected in my mongoose apps.js file, and I have no error on the connection. But as the form is not displayed, nothing is sent on mongodb atlas too.

I have this message : SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at exports.createThing .

exports.createThing = (req, res, next) => {
  const thingObject = JSON.parse(req.body.thing);
  delete thingObject._id;
  const thing = new Thing({
    ...thingObject,
    imageUrl: `${req.protocol}://${req.get("host")}/images/${
      req.file.filename
    }`,
  });
  thing
    .save()
    .then(() => res.status(201).json({ message: "
registered object !" }))
    .catch((error) => res.status(400).json({ error }));
};

How to check if array of objects contains any value from array

Hi so i have an array of integers which i have been trying to check against my array of objects. I only want to check that ANY of the values in the array are within the objArray, it does not need to be ALL.

const objArray = [{id: 1},{id: 2},{id: 3}]

const array = [1, 2]

This is what i tried but i think i am probably way off the logic, i end up getting false every time i run the below code.

array.includes(objArray.some(o => o.id))

Essentially my overall goal to is to validate that any return true and then continue with code otherwise throw an error.

Thank you in advance!

Image does not load by contnent script with CSS

In a Chrome extension I try to load an image with a content script using CSS. The image does not load.

Here is the manifest.json:

"content_scripts": [
   {
     "matches": ["<all_urls>"],
     "css": ["content.css"],
     "js": ["content.js"],
      "run_at": "document_end",
      "all_frames": true
   }
 ]

With the content.js I add an element to pages which indeed it successfully gets added every time.

And here is the CSS code:

#my_added_element {
    background: url('chrome-extension://__MSG_@@extension_id__/icon.png') right center;
}

I also tried:

#my_added_element {
    background: url('chrome-extension://__MSG_@@extension_id__/content/icon.png') right center;
}

in case there was a restriction about loading resources from another directory.

In both cases the CSS script gets injected as expected, as I can confirm using the developer tools, and if I click on the image’s CSS link in the developer tools it opens without issues in a new tab.

So what prevents the load of the image in pages? What else should I check?

Meteor Calls and Methods – Sent and received objects differ

I’m using Meteor and Typescript and would like to send a TypeScript object using Calls and Methods. I’ve noticed the object that is received when using Meteor.call() is different to the object that is sent.

I’m expecting the uniqueColumns field to be an array when received in the Meteor.call().

Class to send

export class Template {
  _id: string;
  userId: string;
  uniqueColumns: string[] = [];
}

Meteor Method – uniqueColumns is an array when printed

Meteor.methods({
  getTemplates(): Array<Template> {
    return TemplateCollectionManager.getInstance().getAll();
  }
});

Meteor Call – uniqueColumns is an Object

Meteor.call('getTemplates', null, (err: any, res: Array<Template>) => {
  if (err) {
    console.error(err);
  } else {
    console.log(res);
    callback(res);
  }
});

What is the correct method of sending/receiving a TypeScript object with Meteor Calls and Methods?

ReactJS. I try to make dynamic input field together using react-calendar package

I want to build a dynamic form using react-calendar and input field input (type: time). Whenever a user wants to insert their times in a specific date, the input field will be reset to the first index and will need to enter their times.

I have managed to make the input field dynamic but I cannot get all the arrays with the same ISO DateTime value.

Here is the link to my sandbox for the case
https://codesandbox.io/s/staging-rgb-m8g9j?file=/src/App.js

How do i make my bot delete embeds and not my messages before them?

I’m beginner in js and I’m trying to make my music bot delete embeds made by embedbuilder function. Example: I’m using play command and bot has to send 2 embeds first one saying it’s searching and then second showing results. It deletes my command and then…crash

throw new DiscordAPIError(data, res.status, request);

DiscordAPIError: Unknown Message

I’m new to Dc js v13 btw
Here’s embed builder function code

function embedbuilder(client, message, color, title, description, thumbnail) {
    try{   let embed = new Discord.MessageEmbed()
        .setColor(color)
        .setFooter(client.user.username, client.user.displayAvatarURL());
    if (title) embed.setTitle(title);
    if (description) embed.setDescription(description);
    if (thumbnail) embed.setThumbnail(thumbnail)
    return message.channel.send({ embeds:  }).then(setTimeout(() => message.delete(), 5000));
}catch (error){
    console.error(embed)
 }
}

This code is result of me trying to find solution.Now “play” command code

else if (command === "play" || command === "p") {
        embedbuilder(client, message, "#fffff0", "Searching!", args.join(" ")).catch(console.error)
        return distube.play(message, args.join(" "));

And code making bot show results

.on("searchResult", (message, result) => {
        try{    let i = 0;
        return embedbuilder(client, message, "#fffff0", "", `**Choose**n${result.map(song => `**${++i}**. [${song.name}](${song.url}) - `${song.formattedDuration}``).join("n")}n*I will wait*`).catch(console.error)
    }catch (error){
        console.error
     }
    })

I wonder if making separate timeouts would be better, but I already tried to and I gave up.
discord.js: 13.3.1 (v12 before for long time, new to v13)
distube: 3.0.4
By the way how do i fix that?

if (message.content.includes(client.user.id)) {
       return message.reply(new Discord.MessageEmbed().setColor("#fffff0").setAuthor(`${message.author.username}, My prefix is ${prefix}, please type ${prefix}help to see my commands`, message.author.displayAvatarURL({ dynamic: true })));
    }

When i try to ping my bot it says
throw new DiscordAPIError(data, res.status, request);
^

DiscordAPIError: Cannot send an empty message

How to check if image loads and set it as background-image of a cloned template

I have the following HTML template:

<template id="type1">
  <div class='type1'>
    <a>
      <div class='poster'></div>
      <div class='content'>
        <div class='title'></div>
        <div class='description'></div>
      </div>
    </a>
  </div>
</template>

I’m calling for some API and receive a list of objects with this structure:

[{
  id: 'someid',
  poster: 'some_image_url',
  url: 'some_link_url',
  title: 'Title',
  description: 'description'
}, {...}]

I run in loop on all objects and for each create a clone of the template:

const sonstruct = data => {
  const template = document.querySelector('#type1')
  const clone = template.content.cloneNode(true)
  clone.querySelector('a').setAttribute('href', data.url)
  clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
  clone.querySelector('.title').textContent = data.title
  clone.querySelector('.description').textContent = data.description
  return clone
}

So far everything works just fine. The problem begins when I decide to check if the image in the poster link is loaded, and if not – set some default image. First I tried to do the following (instead of clone.querySelector('.poster')):

const img = new Image
img.onload = function() {
  clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
}
img.onerror = function() {
  clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
}
img.src = data.poster

And I received the following error: clone.querySelector(...) is null

I tried to use closures:

img.onload = (function (clone) {
  return function () {
    clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
  }
})(clone)
img.onerror = (function (clone) {
  return function () {
    clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
  }
})(clone)

Alas, same result, same error.

I also tried to use .apply(clone) on the methods above, however in that case all the images were set to default image in the onerror method, even though the URL in data.poster did return an image.

Why is this happening and how to make it work?

How can I publish a website using my own computer? [closed]

assuming I have HTML, CSS and JavaScript files and now want to upload them to a web server so that anyone can access them via a domain or IP.

  • How do I proceed?
  • Do I need a domain (in form of: www.[name].de) or
    does an IP address work?
  • How do I publish the code
  • How do I make
    sure that the visitors of the website can interact with each other,
    e.g. through a chat?

Thanks in advance

How to make directories and files appear on the server, node.js

I have a code, it shows folders, I can navigate through them and files too, but this only works in the console:

`

const fs = require('fs/promises');
const fsToRead = require('fs')
const path = require('path');
const inquirer = require('inquirer');
const yargs = require('yargs');
const { lstatSync, readdirSync } = require('fs');
const http = require('http');
const url = require('url');
const options = yargs
    .options('p', {
        describe: 'Pattern',
        default: ''
    })
    .options('d', {
        describe: 'Path to directory', 
        default: process.cwd()
    }).argv;

console.log(options);

class itemsList {
    constructor(path, fileName) {
        this.path = path;
        this.fileName = fileName;
    }
    get folders() {
        return lstatSync(this.path).isDirectory();
    }
}

let executionDir = process.cwd();

const start = async () => {
    const list = await fs.readdir(executionDir);
    const items = list.map(fileName =>
        new itemsList(path.join(executionDir, fileName), fileName));
    const item = await inquirer.prompt([
        {
            name: 'fileName',
            type: 'list',
            message: `Choose: ${executionDir}`,
            choices: items.map(item => ({name: item.fileName, value: item})),
        }
    ]).then(answer => answer.fileName);
    
    if (item.folders) {
        executionDir = item.path;
        return await start();
    } else {
        const data = await fs.readFile(item.path, 'utf-8');

        if (!options.p) {
            console.log(data)
        }
        else {
            const regExp = new RegExp(options.p, 'igm');
            console.log(data.match(regExp));
        }
    }
}

start();

`

HOW TO IMPLEMENT THAT SHE SHOWS ON THE PAGE OF THE BROWSER, THAT IN THE WEB VERSION I COULD GO TO THE FOLDERS, IF THIS IS A FILE SHE WOULD SHOW ITS CODE, I WOULD NOT HAPPEN IT!

Why don’t HTML suggestions work in my Javascript file which has HTML elements in it?

I am creating and HTML web component in JavaScript. However, when i start writing the HTML in it the suggestions and completions don’t work. Below is the code:

class CardComponent extends LitElement {

    render() {
        return html`
        
        <div class="card">
            <h2>Title</h2>
            <p>11.12.2021</p>
            <p>Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla</p>
        </div>

        <style>
            .card {
                width:400px;
                bordr:2px solid red;
                padding:10px;
            }
        </style>

        `
    }
}

I had to type the entire HTML manually myself except for the curly braces which close on their own. Also, the tags in this part were not color coded in the IDE.

How do I enable the suggestions and auto completion?