Object properties are undefined even it show up in the console log

I am using react-query useMutation in order to call the api and get the response. I am trying to read an array inside the response object. But it is undefined even response can be logged using console log.

This is my useMutation function.

const { mutate, isLoading, data={}, error={} } = useMutation(redeemTicket, {
onSettled: (successData, err) => {
  if (successData && !successData.error) {
    setIsRedeemSuccess(true)
    analytics().logEvent('redemption_success', {
      type: 'scan',
      eventId: selectedEvent.id,
    });
  } else {
    setIsRedeemSuccess(false)
    analytics().logEvent('redemption_failed', {
      error: successData?.error || err?.error || err?.message,
      type: 'scan',
      eventId: selectedEvent.id,
    });
  }
},

});

These are my sample logs.

const scannedData = data?.scanned;
console.log("========================data ", data); // {"scanned":[{"id":1629,"assetId":205042,"redeemStatus":0,"redeemMediaUrl":"https://api.test-yh.io/api/getPubFile?id=1304","section":"3","rowNo":"H2","seatNo":"20","category":"",}],"count":1}
console.log("========================scannedData ", scannedData); // undefined

Can anyone help me on this?

I am having problem when adding a working update button inside material ui datagrid v5.6.1

I am trying to add a button inside my material ui datagrid row.

My datagrid component

<DataGrid
    rows={adminStorage}
    columns={columns}
    autoPageSize
    getRowId={(logistics) => logistics._id }
    autoHeight
    headerHeight={60}
    pageSize={100}
    className={classes.root}
/>

the column

    {
        ...
        field: "update",
        align:"left",
        headerAlign: "left",
        headerName: "Update",
        renderCell: (cellValues) => {
            return (
                <Button pL={2} onClick={updateHandler} variant="contained" color="primary">
                    update
                </Button>
            )
        }
    },

the update handler

const updateHandler = (cellvalues) => {
     console.log("The data botained fron the handler is", cellvalues)
}

I want it to work in such a way that when the button is clicked it links to another page that has edit form as well as getting that specific row object and its id

What should i do?

Use appendto() to move div to another div but it duplicates content

I’m having problems with my code. I’m trying to move a <div> to another <div> when the browser windows is below a certain screen size but it moves all of them. For example, the code I have below:

<div class="link-attach-no-comment">
    <div class="comment-contain-left"></div>
    <div class="link-img"></div>
</div>

is suppose to look like this:

<div class="link-attach-no-comment">
    <div class="link-img"></div>
    <div class="comment-contain-left"></div>
</div>

But if I have more than of the above, it copies all of <div class="link-img"></div> and makes duplicates.

<div class="link-attach-no-comment">
    <div class="link-img"></div>
    <div class="link-img"></div>
    <div class="link-img"></div>
    <div class="comment-contain-left"></div>
</div>

How do I prevent duplicate div from copying? My JS file looks like this:

jQuery(document).ready(function($){
  $(window).resize(function() {
    if (window.matchMedia( "(max-width: 1023px)" ).matches) {
        $(".link-outside .link-attach-no-comment .link-img").clone().insertBefore(".link-outside .link-attach-no-comment");
    } else {
        $(".link-outside .link-attach-no-comment .link-img").clone().insertAfter(".link-outside .link-attach-no-comment");
    }; 
  }).resize();
});

How to create html element using JavaScript and create class/id to it

I want to create html element using JavaScript and add class or id, so I can edit this element later.

I know how to create element:

<html>

<body>
  <div id="new">
    <p id="p1">a</p>
    <p id="p2">b</p>
  </div>
  <script>
    var tag = document.createElement("p");
    var text = document.createTextNode("c");
    tag.appendChild(text);
    var element = document.getElementById("new");
    element.appendChild(tag);
  </script>
</body>

</html>

But I don’t know how to add class or id to element that don’t have id or class at beggining.

how can i store data in json file Continuous for discord js

I want to take the message information from the user and save it in a JSON file and this data is constantly added, but with the following code, this data is constantly replaced.
and I don’t replace data I want to add data
this is my code :

const fs = require("fs");
const { Client, Intents } = require("discord.js");

const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
const now = new Date();
const obj = {
  table: [],
};
let confirm = false;
const { badWords } = require("../badWordList.json");
client.on("message", async (message) => {
  if (message.author.bot) return;
  for (let i = 0; i < badWords.length; i++) {
    if (message.content.toLowerCase().includes(badWords[i].toLowerCase()))
      confirm = true;
  }
  if (confirm) {
    obj.table.push({
      name: message.author.username,
      date: `${now.getFullYear()}/${now.getMonth()}/${now.getDate()}`,
      message: message.channel.messages.channel.lastMessage.cleanContent,
    });
    fs.writeFile("myjsonfile.json", JSON.stringify(obj), function (err) {
      if (err) throw err;
      console.log("complete");
    });
  }
});

Use of “`self.[]“` in method definition in ruby

Actually, I am experienced in NodeJS but I am very new to Ruby, I cannot understand how this piece of ruby code is working, can someone explain what exactly the self.call method and self.[] methods are doing in this Ruby code ?.

1. class Mine::Container
2. 
3. def self.call
4.    @containers || {}
5. end
6.
7. def self.[] namespace
8.    @containers ||= Hash.new{|h, k| h[k] = new }
9.    @containers[namespace]
10.  end
11.end

What exactly self.call, self.[] method is doing ?.
What would I get back if I call Mine::Container.(). ?.

How do I connect multiple EventListeners so they work together as a filter system?

enter image description hereI am trying to build a filtering system using select tags. So I decided to go with removing and adding classes to my elements. Every filter works fine by themselves, but I want them to work together. For example when I choose Bali Papuan and then choose a process method I want to show only Bali Papuan with this Process method and so on. How do I make this right?

var clear = document.getElementById('clear_button')
var island = document.getElementById('select_island')
var type = document.getElementById('select_type')
var process_method = document.getElementById('select_process')
var grade = document.getElementById('select_quality')
var available = document.getElementById('select_available')
var cp = document.getElementById('select_cp')
clear.onclick = function(){
  island.value = "all";
  type.value = "all";
  process_method.value = "all";
  grade.value = "all";
  available.value = "all";
  cp.value = "all";
}

const filterBox = document.querySelectorAll('.box')


var island = document.getElementById('select_island')
var type = document.getElementById('select_type')
var pm = document.getElementById('select_process')
var quality = document.getElementById('select_quality')
var available = document.getElementById('select_available')
var cp = document.getElementById('select_cp')


clear.addEventListener('click', function(){
  filterBox.forEach(elem =>{
    elem.classList.remove('hide')
  })
})


island.addEventListener('change', function(){
  value = this.value
  filterBox.forEach(elem =>{
    if (!elem.classList.contains(value)&& value !== 'all'){
      elem.classList.add('hide')
    }if (elem.classList.contains(value)){
      elem.classList.remove('hide')
    }  
  
  })})



  type.addEventListener('change', function(){
    value = this.value
    filterBox.forEach(elem =>{
      if(!elem.classList.contains(value) && value !== 'all'){
        elem.classList.add('hide')
      }if (elem.classList.contains(value)){
        elem.classList.remove('hide')
      }
    })})








pm.addEventListener('change', function(){
    value = this.value
    filterBox.forEach(elem =>{
      if(!elem.classList.contains(value) && value !== 'all'){
        elem.classList.add('hide')
       }if (elem.classList.contains(value)){
        elem.classList.remove('hide')
        }
      })})


      quality.addEventListener('change', function(){
        value = this.value
        filterBox.forEach(elem =>{
          if(!elem.classList.contains(value) && value !== 'all'){
            elem.classList.add('hide')
          }if (elem.classList.contains(value)){
            elem.classList.remove('hide')
          }
        })})


        available.addEventListener('change', function(){
          value = this.value
          filterBox.forEach(elem =>{
            if(!elem.classList.contains(value) && value !== 'all'){
              elem.classList.add('hide')
            }if (elem.classList.contains(value)){
              elem.classList.remove('hide')
            }
          })})


          cp.addEventListener('change', function(){
            value = this.value
            filterBox.forEach(elem =>{
              if(!elem.classList.contains(value) && value !== 'all'){
                elem.classList.add('hide')
              }if (elem.classList.contains(value)){
                elem.classList.remove('hide')
              }
            })})

The code above simply manages clear_all button. Also it takes values from select tags and depending on it’s output adds ‘hide’ class to my divs.

Javascript’s XHR.upload.onprogress event fires on staging, but not on production. Puzzling

First of all, the code base is identical (I ran sudo git pull on both servers).

I’ve kept my staging and production environments as identical as possible (which is the whole point), but somehow my progress bars are only working in staging, not production.

Tested in multiple browsers, the disparity remains. Both served over https.

Which leads me to suspect some configuration on production is causing the disparity, can’t tell if it’s nginx, gunicorn, supervisord, or something else. It makes no sense to me.

I’m using Python/Django + Ubuntu for my backend if that matters.

Video: https://www.loom.com/share/3db49bb8edd0412ea267ab1687a86273

Anyone has any idea where the bug may be?

Express Validator – If exists for nested array of object

{
    "orderId": "3",
    "storeId": "1",
    "products": [
         "productId": "123",
        {
         "prescriptions" : [{
            "eye": "1",
            "sph": "1",
            "cyl": "1",
            "add": "1",
            "axis": "1"
        }],
            "lensItems": {
                "lensId": "1",
                "lensType": "1",
                "lensCoating": "1",
                "index": "1",
                "price": "3000"
            },
            "frameSize": {
                "a": "1",
                "b": "1",
                "ed": "1",
                "fh": "1",
                "d": "2"
            },
            "counterSale": false
        }
    ]
}

I want to check the prescriptions only if the lensItems exists.

I have tried this,

 body('products.*.prescriptions')
        .if(body('products.*.lensItems').exists())
        .exists()
        .withMessage('prescriptions not exists')
        .isArray()
        .withMessage('prescriptions is not an array')
        .notEmpty()
        .withMessage('prescriptions is empty'),

Its working when I check with string like below,

 body('products.*.prescriptions')
            .if(body('products.*.productId').exists())
            .exists()
            .withMessage('prescriptions not exists')
            .isArray()
            .withMessage('prescriptions is not an array')
            .notEmpty()
            .withMessage('prescriptions is empty'),

I want to the compare array of object with object . If any more regarding this please comment, I will share you much informations which are possible. Thanks in advance

All Combinations of Riddle

I need a function in Javascript that takes in a String like this:

var str = '2?5?8?1?4?7?9?2?3'

and generates all possible combinations of the riddle with all question marks being substituted with basic mathematical operators (+-*/).

How would you go about that? And how would you do it for a dynamic length of riddles?

How to add html code based on the screen sizes using Javascript?

I want to make add some code to the HTML dom according to the screen sizes. I want to totally remove the code when the screen size is something instead of still having the code and doing display: none. How can I do it?

<div id="main">
  <h1>One</h1>
</div>
const main = document.getElementById('main');

if(window.innerWidth <= 400) {
       main.innerHTML = '<h2>Added By js</h2>';
 }
 else {
 main.innerHTML = '';
 }

Blank content is displayed when trying to open .pdf in another tab using React and Express

I am trying to open a .pdf in another tab that is stored in the server’s file system (I am using Express, React and MySQL).
When the user clicks the “See” button, the displayCV function is executed, and a new tab is open, but the .pdf content is blank even though the new tab shows the correct number of pages the .pdf contains.

The flow goes like this:

JobItem.jsx

const displayCV = async (e) => {
   e.preventDefault();
   await displayCurriculum();
};

JobContext.js

const displayCurriculum = async () => {
  const { id } = params;

  const response = await axios.get(`/api/jobs/${id}/cv`);
  // console.log(response);

  const file = new Blob([response.data], {
    type: "application/pdf",
  });

  const fileURL = URL.createObjectURL(file);
  const pdfWindow = window.open();
  pdfWindow.location.href = fileURL;
};

The backend looks like this:

jobRoutes.js

const express = require("express");
const router = express.Router();
const { displayCurriculum } = require("../controllers/jobController");
router.route("/:id/cv").get(displayCurriculum);

jobController.js

const displayCurriculum = asyncHandler(async (req, res) => {
  try {
    const { id } = req.params,
      q = `SELECT curriculum FROM jobs WHERE idjobs = ?`,
      doc = await pool.query(q, [id]);

    const fileName = doc[0].curriculum;

    // const data = fs.readFileSync(filesPath + "\" + fileName);
    res.setHeader("Content-Type", "application/pdf");
    res.sendFile(fileName, { root: filesPath }, (err) => {
      if (err) console.log(err);
      else console.log("Sent: ", fileName);
    });
  } catch (error) {
    console.log(error);
  }
});

If I use Postman and hit the API’s endpoint (/api/jobs/${id}/cv) the .pdf is displayed correctly in Postman. When hitting the endpoint from the frontend I get the following
Image with blank .pdf content

How can I display the .pdf content in the new tab?

Cannot find module ‘vue/dist/vue.esm’

I just created a new rails + vue.js app, but Vue is throwing an error in the browser console and does not populate the data in {{message}}

I’m using VS Code on Windows and I followed this guide: https://medium.com/swlh/how-to-integrate-vue-js-with-rails-6-5bd4c6263b18

The browser console shows this error: Uncaught SyntaxError: Unexpected token '!'

and references the following JS code:

!(function webpackMissingModule() { var e = new Error("Cannot find module 'vue/dist/vue.esm'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()).use(vue_turbolinks__WEBPACK_IMPORTED_MODULE_0__["default"]);
document.addEventListener('turbolinks:load', function () {
  var app = new !(function webpackMissingModule() { var e = new Error("Cannot find module 'vue/dist/vue.esm'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())({
    el: '#hello',
    data: function data() {
      return {
        message: "Can you say hello?"
      };
    },
    components: {
      App: _app_vue__WEBPACK_IMPORTED_MODULE_2__["default"]
    }
  });
});
...