How to preserve value from promise for use in subsequent code?

I’m doing a database query and then processing the data so that it will yield a single numeric value. That value needs to be used in a subsequent array.

The array definition currently looks like this (below). The problem is all_kdm_coverage is a promise. But what I need to do is extract the numeric value from the promise.

const scrolls = [
    {
        title: "Kadena de Mano",
        link: "./Kdm",
        coverage: all_kdm_coverage
    },
]

Here is a larger snippet to provide more context


async function GetCoverage(scroll_path) {
    const apiName = 'foo';
    const path = '/scrolls/' + scroll_path;
    const myInit = {
        headers: {},
        response: false,
    };
    const response = await API.get(apiName, path, myInit)
    console.log('response:',response)
    return response.Items
}

function GetScroll(scroll_name, scroll_array) {
    const scroll_data = scroll_array.find(scroll => scroll.Scroll === scroll_name);
    console.log('scroll_data:',scroll_data)
    return scroll_data
}

let dataGlobal;
const getData = () => (dataGlobal ??= GetCoverage("all"));

const all_kdm_coverage = getData().then(
    (data) => {
        const  kdm_entry = GetScroll("kdm", data)
        const coverage = kdm_entry.Coverage
        console.log('kdm coverage:',coverage)
        return coverage
    }
)

const scrolls = [
    {
        title: "Kadena de Mano",
        link: "./Kdm",
        coverage: all_kdm_coverage
    },
]

What’s the best way to set the coverage: value in scrolls?

TypeError: r.at is not a function error on mobile but not on desktop

I am building a web application using Next.js with Turbo Pack.

I have encountered an issue where I am getting a

TypeError: r.at is not a function

error on my mobile device (iPhone) when I access the website using Google Chrome.

I am using chrome://inspect

However, I am not getting this error when I access the website on my desktop using the Google Chrome developer tools and setting it to an iPhone SE.

I have checked my code and I am not using any function called “at”. I have tried clearing my browser cache and cookies on my mobile device, but the error persists.

This error is breaking my website and preventing it from functioning correctly on mobile devices.

I would appreciate any suggestions or insights on how to resolve this issue. Thank you in advance.

Jest test in React Native fails with error message [enter image description here]

Iam trying to test my app in react native using jest but i got this error

I tried to solve it in many ways and still got the error
Please help me to solved

The error i got is :
[text](error )

pakage.json :
pakage.json

pakage.json

babel.config.js :
babel.config.js

I tried to use transformIgnorPatrerns also and still the error

please i will be very grateful if someone help me to solve the error because I’ve been trying to solve it for a week until now ..

Rotating proxy doesn’t work with fetch (works on HTTP, but not HTTPS)

How do I get my IP to rotate on every fetch request made through selenium?

I’m trying to get my IP to rotate on selenium (using a rotating proxy provider), the IP changes every time I refresh page or use fetch on ‘http://api.myip.com/’ but it sticks to the same IP on ‘https://api.myip.com/’. (difference is HTTP and HTTPS)

I’m guessing it like sticks to the session or something, but how do I get it to rotate like it does on HTTP? I tried fetch with header “connection”: “close” but that doesn’t work either.

Here’s my proxy (you can test it out and see the IP changes on HTTP):

gate.smartproxy.com:7000:user862356:nO74GySc8v5zfpmnJf

This is the code i’m using

fetch("http://api.myip.com/", {
  "headers": {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
    "cache-control": "max-age=0",
  },
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": null,
  "method": "GET",
  "mode": "cors",
  "credentials": "omit"
});

Access Class variables inside navigator.permissions.query [duplicate]

I am trying to request permission from the user to record audio using AngularJs.

I have this method in my Component Class, but the class variables are not accessible using this.

public recordAnswer(event: any) {

    this.recording = true;
    this.toastr.error('Something went wrong. Try again.'); // this line works

    navigator.permissions.query({name: 'microphone'}).then(function (result) {

        console.log(result);

        if (result.state == 'granted') {
            // start recording audio
        } else if (result.state == 'prompt') {

        } else if (result.state == 'denied') {
            console.log(this.psp); // this line does not work
            this.toastr.error('Something went wrong. Try again.'); // this line does not work
        }

        result.onchange = function () {};
    });

}

I am getting this error:-

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading ‘psp’)
TypeError: Cannot read properties of undefined (reading ‘psp’)

How can I access class variables so I can display a toastr.error to inform user to give permission?

How import javascript module which exporting with spread operator?

Here is the index.js of kafkajs library. As I want to override the kafkajs, so I only want to import fews module from kafkajs library. But how can I import the “…errors” in my new created index.js.

Org index.js

const Kafka = require('./src')
const PartitionAssigners = require('./src/consumer/assigners')
const AssignerProtocol = require('./src/consumer/assignerProtocol')
const Partitioners = require('./src/producer/partitioners')
const Compression = require('./src/protocol/message/compression')
const ConfigResourceTypes = require('./src/protocol/configResourceTypes')
const ConfigSource = require('./src/protocol/configSource')
const AclResourceTypes = require('./src/protocol/aclResourceTypes')
const AclOperationTypes = require('./src/protocol/aclOperationTypes')
const AclPermissionTypes = require('./src/protocol/aclPermissionTypes')
const ResourcePatternTypes = require('./src/protocol/resourcePatternTypes')
const { isRebalancing, isKafkaJSError, ...errors } = require('./src/errors')
const { LEVELS } = require('./src/loggers')

module.exports = {
  Kafka,
  PartitionAssigners,
  AssignerProtocol,
  Partitioners,
  logLevel: LEVELS,
  CompressionTypes: Compression.Types,
  CompressionCodecs: Compression.Codecs,
  ConfigResourceTypes,
  AclResourceTypes,
  AclOperationTypes,
  AclPermissionTypes,
  ResourcePatternTypes,
  ConfigSource,
  ...errors,
}

Overrided index.js:

const { Kafka } = require('kafkajs')

const PartitionAssigners = Kafka.PartitionAssigners
const AssignerProtocol = Kafka.AssignerProtocol
const Partitioners = Kafka.Partitioners
const LEVELS = Kafka.LEVELS
const CompressionTypes = Kafka.CompressionTypes
const CompressionCodecs = Kafka.CompressionCodecs
const ConfigResourceTypes = Kafka.ConfigResourceTypes
const AclResourceTypes = Kafka.AclResourceTypes
const AclOperationTypes = Kafka.AclOperationTypes
const AclPermissionTypes = Kafka.AclPermissionTypes
const ResourcePatternTypes = Kafka.ResourcePatternTypes
const ConfigSource = Kafka.ConfigSource

const { isRebalancing, isKafkaJSError, ...errors } = Kafka.errors // !!! will return error

module.exports = {
  PartitionAssigners,
  AssignerProtocol,
  Partitioners,
  logLevel: LEVELS,
  CompressionTypes,
  CompressionCodecs,
  ConfigResourceTypes,
  AclResourceTypes,
  AclOperationTypes,
  AclPermissionTypes,
  ResourcePatternTypes,
  ConfigSource,
  ...errors,
}

Prime React Drop Down(more data)

**I am using PrimeReact with React, and I’m sending 300,000 data items to a dropdown via the backend. However, I’m experiencing issues with the filtering feature. If the scroll is at the bottom, it freezes when I perform a search. But if the scroll is at the top, I don’t encounter any problems when searching.
I have set the item size to 20 using a virtual scroller.
**

How to Implement Redis Caching in my API to Retrieve New and Different Posts Every Time?

I am trying retrieve some posts from my MongoDB database but it was taking a lot of time to get posts to i impleted redis caching in my API but now i am facing a problem that its returning same posts from cache every time i hit the API How to get new and different posts from redis cache whenever i hit the API? Like Instagram uses redis and they give me new and different posts every time i scroll so fast How to balance things in my case?

router.get('/posts', async (req, res) => {
    try {
        const cacheKey = `posts:${req.query.page || 1}`;
        const cacheTTL = 60;

        const cachedData = await redisClient.json.get(cacheKey, '$');

        if (cachedData) {
            console.log('Data fetched from Redis cache');
            return res.json(cachedData);
        }

        const page = Number(req.query.page) || 1;
        const limit = Number(req.query.limit) || 50;
        const skip = (page - 1) * limit;

        const result = await User.aggregate([
            { $project: { posts: 1 } },
            { $unwind: '$posts' },
            { $project: { postImage: '$posts.post', date: '$posts.date' } },
            { $sort: { date: -1 } },
            { $skip: skip },
            { $limit: limit },
        ]);

        await redisClient.json.set(cacheKey, '$', result, 'EX', cacheTTL);

        console.log('Data fetched from MongoDB and cached in Redis');
        res.json(result);
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Internal server error' });
    }
});

React Hook Form watch returning old value

I have fields rendered dynamically in a grid (with Edit for each row)
On click of Edit for each row, I open a modal dialog and render the “input” via a Field component I have.

In that component, I have

const myGridFieldId = field.id + "-" + gridRowIndex; //"firstNameField-0"
watch(myGridFieldId);

On save of modal dialog, I update my state (context object) and also set all the default values based on that state and pass it back to the Form.

Now, the issue is, as I save the first 2 rows one-by-one with updated values and do Edit again for the first row (“firstNameField-0”) and at that point of time,

watch(myGridFieldId)

returns me the old value, instead of the updated/earlier saved value

Even though, after I save and I console log my defaultValues, I can see defaultValues.”firstNameField-0″ has the updated value.

Not sure why watch is returning me the old value ?

get data from realtime database against fire store users ids

Get data from realtime database against fire store users ids.

      /////////  fetchFirestoreData ////////////////
      fetchFirestoreData();
  


  const dbRef = firebase.database().ref();
const usersRef = dbRef.child('module');


 readUserData(); 


function readUserData() {
  var userListUI = document.getElementById("user-list");

  usersRef.on("value", function(snap) {
    userListUI.innerHTML = "";

    snap.forEach(function(childSnap) {
      var key = childSnap.key;
      var $li = document.createElement("li");

      $li.innerHTML = key;

      $li.setAttribute("data-user-key", key);
      $li.addEventListener("click", userClicked);
      userListUI.append($li);
    });
  });
}


function userClicked(e) {
  var userDetailUI = document.getElementById("user-detail");

  var userID = e.target.getAttribute("data-user-key");
  const userRef = dbRef.child('module/' + userID);

  userRef.on("value", snap => {
    userDetailUI.innerHTML = "";

    const userData = snap.val();

    for (let key in userData) {
      var $p = document.createElement("p");
      $p.innerHTML = key + ": " + userData[key];
      userDetailUI.append($p);
    }
  });
}

How to append text to a file at client’s machine in Blazor WebAssembly

I have an app in Blazor Webassembly (.NET 6) and I want to write (specifically append) any exceptions thrown to a file at client’s pc. I don’t want to involve backend for this.

I have tried some C# methods (such as WriteAsync of StreamWriter and WriteAllText of File) without any luck.

I was wondering if it is even possible to do something like that because the app is running in a browser. Is there a javascript method that achieve my goal? Or any way?

Thanks for your time!

I am getting this error Uncaught TypeError: $(…).waypoint is not a function and slider is not working in the page

i add this library to my code but still i did not get the result and the slider is not working
here is the reference page link

code

fl_theme.initSellCar = function(){
        $('#step01').waypoint(function() {
            $(".b-submit__aside-step").removeClass('m-active');
            $(".b-submit__aside-step-inner").removeClass('m-active');
            $(".step01").addClass('m-active');
            $(".step01 .b-submit__aside-step-inner").addClass('m-active');

        }

i use this library link of java library somebody recommend it but not working

I can’t get ApolloServer to return connected nodes with GraphQL

I’m currently working on a project where I retrieve data from a Neo4j database using a GraphQL query. The query returns a central Company node along with its connected nodes, which can be of type Company or Person. I’m having trouble mapping the connected nodes properly in my JavaScript code.

Here’s an excerpt of the code I’m using:

const { ApolloServer, gql } = require('apollo-server');
const neo4j = require('neo4j-driver');
const { GraphQLJSON } = require('graphql-scalars');

const typeDefs = gql`
  scalar JSON

  type Company {
    id: ID!
    orgNo: String!
    companyName: String!
    address: String!
    city: String!
    zipCode: String!
    connectedNodes: [Node]
  }
  
    type Person {
    id: ID!
    role: String
    ZipCode: String
    Street: String
    test_id: String
    label: String
    City: String
    RoleCode: String
    Name: String
  }


  type Node {
    id: ID!
    labels: [String]
    properties: JSON
  }

  type Query {
    company(orgNo: String!): Company
  }
`;


const driver = neo4j.driver(
  'bolt://localhost:7687',
  neo4j.auth.basic('neo4j', 'password')
);

const resolvers = {
  JSON: GraphQLJSON,

  Query: {
    company: async (_, { orgNo }) => {
      const session = driver.session();
      const result = await session.run(
        `MATCH (source:Company {OrgNo: $orgNo})
        OPTIONAL MATCH path = (source)-[*1..3]-(target)
        WHERE NONE(rel IN relationships(path) WHERE rel.RoleCode IN ['REV', 'SU'])
        RETURN source, COLLECT(DISTINCT target) AS connected_nodes`,
        { orgNo }
      );
      await session.close();
      
      const companyNode = result.records[0]?.get('source')?.properties;
      if (!companyNode) return null;
      
      const connectedNodes = result.records[0]?.get('connected_nodes')?.map(record => {
        const nodeType = record && record.labels?.[0];
        const nodeProperties = record && record.properties;
        


        if (record && record.labels.includes('Company')) {
          return {
            id: record.identity?.toString() || null,
            labels: record.labels || [],
            properties: nodeProperties || {}
          };
        } else if (record && record.labels.includes('Person')) {
          return {
            id: nodeProperties && nodeProperties['test_id']?.toString() || null,
            labels: record.labels || [],
            properties: nodeProperties || {}
          };
        }
        
        
        return node;
      }) || [];
      
      
      // console.log(connectedNodes)

      const company = {
        id: companyNode && companyNode['identity']?.toString() || '',
        orgNo: companyNode && companyNode['OrgNo'] || null,
        companyName: companyNode && companyNode['CompanyName'] || null,
        address: companyNode && companyNode['Address'] || null,
        city: companyNode && companyNode['City'] || null,
        zipCode: companyNode && companyNode['ZipCode'] || ''
      };
      

      return company;
    },
  },
};




const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(`Server running at ${url}`);
});

I’ve been able to retrieve the central Company node successfully. However, when trying to map the connected nodes in connectedNodes, I haven’t been able to achieve the desired result. The console.log(connectedNodes) statement outputs an the nodes as list.

I suspect that there might be an issue with the mapping logic or how I’m accessing the properties of each connected node. I’ve tried various approaches, including using optional chaining (?.) and checking for the node type using conditions.

I would greatly appreciate any insights or suggestions on how to properly map the connected nodes in this scenario. Thank you!