Axios POSTing data records to Dynamo, but unable to Axios GET request to find – Javascript/Typescript

I have the following code for POSTing a record via axios to my DB, and then I would like to search for said record by its ID match as well as list all the latest records.

I have confirmed, via checking Dynamo, that the record gets added to the DB but cannot get it to appear when I look for it via the GET /search.

It makes me wonder if I’m somehow making a mistake.

I know that my database has 6000+ records of this same type, so I could just be getting unlucky (as I have not yet included pagination in my queries)… but I’ve tested this about 50 times with 0 retrieval success via the query vs running the same POST and GET via Postman and having about a 50% success rate.

test('post result then search for presence', async () => {
    const trafficAnalyticMessage = buildTrafficAnalyticMessage();

    const result = await axios.post(messagesUrl, trafficAnalyticMessage, {
      headers: {
        'x-api-key': 'redacted',
      },
    });

    const message = result.data as dataMessageApi.Message;
    logger.log(`Message ${util.inspect(message)}`);
    // logger.log(`Result ${util.inspect(result)}`);

    const results = await axios.get(searchUrl, {
      headers: {
        'x-api-key': 'redacted',
      },
      params: {
        type: 'analytic',
        subtype: 'traffic_volumes',
        startTime: 1,
      },
    });

    logger.log(
      'Attempting to search for message with id: ' + JSON.stringify(message.id),
    );

    const messages = results.data as dataMessageApi.Message[];
    const found = messages.find((m) => m.id === message.id);

    logger.log('Message returned from search: ' + JSON.stringify(found));
    // expect(found).toBeDefined();

    let date: string;
    // log length, first and last msg id
    logger.log(`Length of search response:  ${messages.length}`);
    // 1
    logger.log('First ID:  ' + JSON.stringify(messages[0].id));
    date = new Date(messages[0].timestamp!).toUTCString();
    logger.log(`First timestamp: ${date}`);
    // 2
    logger.log('Second ID:  ' + JSON.stringify(messages[1].id));
    date = new Date(messages[1].timestamp!).toUTCString();
    logger.log(`Second timestamp: ${date}`);
    // 3
    logger.log('Third ID:  ' + JSON.stringify(messages[2].id));
    date = new Date(messages[2].timestamp!).toUTCString();
    logger.log(`Third timestamp: ${date}`);
    // 4
    logger.log('Fourth ID:  ' + JSON.stringify(messages[3].id));
    date = new Date(messages[3].timestamp!).toUTCString();
    logger.log(`Fourth timestamp: ${date}`);
    // Fifth from last
    logger.log(
      'Fifth from last ID:  ' +
        JSON.stringify(messages[messages.length - 5].id),
    );
    date = new Date(messages[messages.length - 5].timestamp!).toUTCString();
    logger.log(`Fifth to last timestamp: ${date}`);
    logger.log(
      'Fourth from last ID:  ' +
        JSON.stringify(messages[messages.length - 4].id),
    );
    date = new Date(messages[messages.length - 4].timestamp!).toUTCString();
    logger.log(`Fourth from last timestamp: ${date}`);
    logger.log(
      'Third from last ID:  ' +
        JSON.stringify(messages[messages.length - 3].id),
    );
    date = new Date(messages[messages.length - 3].timestamp!).toUTCString();
    logger.log(`Third from last timestamp: ${date}`);
    logger.log(
      'Second to last ID:  ' + JSON.stringify(messages[messages.length - 2].id),
    );
    date = new Date(messages[messages.length - 2].timestamp!).toUTCString();
    logger.log(`Second to last timestamp: ${date}`);
    logger.log('Last ID:  ' + JSON.stringify(messages[messages.length - 1].id));
    date = new Date(messages[messages.length - 1].timestamp!).toUTCString();
    logger.log(`Last timestamp: ${date}`);

    expect(result).toBeDefined();
    expect(result.status).toBe(201);
  });

This is the output I am getting:

enter image description here

Any help would be greatly appreciated.

**Also, please can you advise me how to add the GET as a .then result of the POST? Or a promise or some kind of 2-part resolution? I have had great trouble figuring out how that works. I’m new to this kind of work.

Thanks so much!!**

what happend re-define setInterval to variable in useEffect hook?

I want to know what happened if I define setInterval function repeatedly to same variable in react hook useEffect.

I checked variable have new setInterval id value every defining.
But I wonder is there instance remained in memory about previous setInterval timer, even if new setInterval defined at same variable??

 useEffect(() => {
    const timer = setInterval(
      () => {
        if (count < elementLength - 1) {
          boolean.current = false;
          setCount(prev => prev + 1);
        } else {
          boolean.current = true;
          setCount(0);
        }
      },
      boolean.current ? 50 : 2500
    );

    return () => {
      clearInterval(timer);
    };
  }, [count]);

The best way to refresh paginated data on the client side?

I have a REST API that implements server-side pagination returning the following data:

{
  items: [
    {
      id: 1,
      name: 1
    },
    {
      id: 2,
      name: 2
    }
  ],
  nextToken: <some-hash-key> // cursor-based
}

How should the client application refresh the list if the resource gets updated (client isn’t aware of the update, so this is a pull model)? I have some ideas:

  1. fetch all resources at a regular interval (like every 10 seconds)
  2. maintain a session ID that rotates every N minutes. When a new session is created, fetch all resources

Both approaches are fundamentally the same idea. The first approach is more costly but allows more real-time updates. The second approach is based on session ID which I think is more idiomatic, but no real-time updates. Is there any other approach?

useState has previous value instead of the current

I’m new to react and I’m trying to understand how it’s working.

I have 2 select inputs and on change event I want to filter the other’s select values based on the first one.

After calling setOptions with the filtered values, they are always one step behind – so I have the previous value each time.

I understand that useState is async and I tried with and useEffect (() => {}, [options])
and I still have the previous values in options.

 const [options, setOptions] = useState<any>()
 const filterOptions = (ids: string[]) => {
        const filteredOptions = list.filter(item=> {
            return list.includes(item.id)
        })
        setOptions(filteredOptions)
    }

Listen/detect the Location URL change in React application

I have a requirement to listen/detect the Location URL change in React application.

I have tried using below code but it changes the location and then gets called.

const location = useLocation();

useEffect(() => {
debugger;
console.log(‘Location changed’);
}, [location]);

Is there a way to listen a URL change before actually changing the location?

Also, Is it possible to find “fromLocation” and “ToLocation”?

I am using “react-router-dom”: “^5.2.0”.

Please help.

Thanks & Regards,
Jyoti

3D Array output in GPU.JS

Hello I’m really new with using GPU.js and I am having trouble understanding createKernel and its output. I want to have a 3D array that stores the outputs from my current function. For example, below, is a gpu matrix multiplication that multiplies matrix a and b, and the result of this function is a 2D array. There are more than one matrix that I want to multiply to a and I want to store all their output in one 3D array.

  const gpu = new GPU();
  const multiplyMatrix = gpu.createKernel(function(a, b) {
    let sum = 0;
    for (let i = 0; i < 10; i++) {
      sum += a[this.thread.y][i] * b[i][this.thread.x];
    }
    return sum;
  }).setOutput([10, 10])

Can anyone please help me. I tried using for loop but it’s so slow and I read because it is expensive to keep using createKernel?

let big3Dmatrix = []
for(let i=0; i<matrices.length; i++){
    big3Dmatrix.push(multiplyMatrix(a,matrices[i]))
}

I would appreciate any help. Thank you!

vue.js ReferenceError (when using resize event)

I’m trying to get the height of the window on resize, but I keep getting the error ReferenceError: calcOfSliderHeight is not defined.

Could anyone let me know what’s going on? Here’s my code

let example = new Vue({
    el: '#example',
    data() {
        return {
            pageIndex: 2,
            posTop: 0,
            posTop2: 0,
        }
    },
    methods: {
        calcOfSliderHeight() {
            let _this = this;
            _this.posTop = (_this.pageIndex - 1) * window.innerHeight
        },
        calcOfSliderHeight2() {
            let _this = this;
            _this.posTop2 = (_this.pageIndex - 3) * window.innerHeight
        },
    },
    mounted: function() {
        let _this = this;

        window.addEventListener('resize', function() {
            calcOfSliderHeight()
            calcOfSliderHeight2()
        });

        _this.posTop = calcOfSliderHeight();
        _this.posTop2 = calcOfSliderHeight2();
    }
});

Multiple image change on click (similar to Cargo image gallery scrub)

I am trying to replicate Cargo’s image gallery scrub using my own HTML/CSS and/or Java. Example of what I want here on image click: https://sage-smith.com/. It is similar to this stack thread (which worked in my code): how to change image onclick javascript function?

However, this solution only offers to click between 2 images. I am trying to do it with multiple images (like an image gallery).

This is what I have so far:

HTML

 <a><img src="collage3.jpg" id="changer" onclick="changeImage(this)"/></a>

Javascript

  function changeImage(element) {
     element.src = element.bln ? "collage3.jpg" : "asset-2.png";
     element.bln = !element.bln;  /* assigns opposite boolean value always */
 }

How to get updated DOM element in javascript code

I am trying to better understand the relationship between how JavaScript updates DOM object.
Here is my html file index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <div id="container">old</div>
  </body>
  <script src="script.js"></script>
</html>

and here is my JavaScript file script.js,

const container = document.getElementById("container");
console.log(container, container.innerHTML);
container.innerHTML = "new";
console.log(container, container.innerHTML);

The console logs the same <div> tag but with different innerHTML which is quiet unexpected:

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

Therefore my 1st question is, what makes it possible for the console to print the same div elements but different innerHTML?


Secondly I made a small change to my script with setTimeout,

let timeout = 30;
setTimeout(() => {
  container.innerHTML = "new";
  console.log(container, container.innerHTML);
}, timeout);

Though container.innerHTML are always printed with different value, as expected, I found out that if the timeout value is above 35. The div tag is almost certainly printed differently with,

<div id="container">old</div> 'old'
<div id="container">new</div> 'new'

Then something I don’t understand happens. When timeout is set below 10, it is almost certain that div tag are printed as,

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

When timeout is set somewhere between 10 and 30ish, the result toggles, meaning sometimes

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

and sometimes

<div id="container">old</div> 'old'
<div id="container">new</div> 'new'

Therefore my second question is, what causes this difference?

Much Appreciated.

‘await’ has no effect on this type of expression, but it does

I am trying to use useRef to auto focus on the mui textfield in the app. However, the textfield only apper after I clicked a button, so it is not initially mounted when the app is rendered. Therefore, the inputRef.current alway return undefined to me when I am using the useEffect hook, because the inputRef is hooked only after the textfield is appeared.

So instead I hook my inputRef.current?.focus() on the buttonlike this:
<Button onClick={() => {toggleCreateWindow(); useInput.current?.focus();}}>

But it won’t work either, until I put it like an inline async function like this:
<Button onClick={ async () => { await toggleCreateWindow(); useInput.current?.focus();}}>

Now it is working properly, but the vscode always remind me 'await' has no effect on this type of expression

Do anybody know why the async function works? I mean the function should not be asynchronous because it is only a setState & toggle window function: const toggleCreateWindow = () => {setOpenCreate(!openCreate);}; Also, why the vscode is giving me this warning?

Much appreicated

How do I filter my web scraping result to not have /n or tab

I am scraping data from a job market website. My scrape return the result that I want but it is full of /n, /t or a lot of spacing. How do I filter the result to get just the contents?

This is my code:

async function start() {

    const browser = await puppeteer.launch({
        headless: true,
        defaultViewport: null,
        args: ['--ignore-certificate-errors']
    });

    var name = ["Job Name"];
    var country = ["Country"];
    var company = ["Company Name"];
    var type = ["Job Type"];
    var salary = ["Salary"];
    var skills = ["Skills Require"];
    var desc = ["Job Description"];
    var req = ["Job Requirements"];
    var resp = ["Job Responsibility"];
    var industry = ["Industry"];

    for (var j = 1; j < 2; j++) {

        const page = await browser.newPage();
        page.setDefaultNavigationTimeout(0);

        await page.goto('https://startupjobs.asia/job/search?q=&job-list-dpl-page=' + j, {
            waitUntil: "networkidle2",
            timeout: 3000000
        });

        console.log('browsing page ' + j);

        for (var i = 1; i < 31; i++) {

            await page.waitForXPath("/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a")
            var b = await page.$x("/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a")
            await b[0].click();

            const elementsToFind = [
                { xpath: "/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a", propName: 'job_name' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[1]/div[2]/div/h6[2]/a', propName: 'country' },
                { xpath: "/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/p[1]/a", propName: 'company' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[3]/p', propName: 'job_type' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/p', propName: 'salary' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[4]/p', propName: 'skills' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div', propName: 'job_description' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[3]/div', propName: 'job_requirement' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[2]/div', propName: 'job_responsibility' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[2]/p', propName: 'industry' },
                // ...
            ];
            /*const elementsToFind2 = [
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[3]/div[1]/div[1]/p/a',      propName2: 'website' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[3]/div[2]/div[1]/div',      propName2: 'about' },
                // ...
            ];*/

            var results = {};

            for (var { xpath, propName } of elementsToFind) {
                await page.waitForXPath(xpath);
                var [el] = await page.$x(xpath);
                results[propName] = !el ? 'Not Found' : await (await el.getProperty('textContent')).jsonValue();
            }

            name.push(results['job_name']);
            country.push(results['country']);
            company.push(results['company']);
            type.push(results['job_type']);
            salary.push(results['salary']);
            skills.push(results['skills']);
            desc.push(results['job_description']);
            req.push(results['job_requirement']);
            resp.push(results['job_responsibility']);
            industry.push(results['industry']);

            //await page.evaluate(() => document.querySelector("#suj-single-jobdetail-wrapper > div.detail-body > div.row > div.col.s12.tabs-wrapper.suj-company-review-tabs-wrapper > ul > li:nth-child(2) > a").click())            
        }
        await page.close();
    }

    await browser.close();

The result that I get is this:

‘n’ +
‘ n’ +
‘ Part-Time n’ +
‘ | n’ +
‘ n’ +
‘ Temporary n’ +
‘ | n’ +
‘ n’ +
‘ Contract n’ +

I want it to be just Part time, temporary and contract.

Using Mantine UI .tsx file within a javascript based react project

I currently am building a fitness website and am looking to use Mantine UI accordion component which is based off Typescript. I built my react project with javascript. Is there a way to create a .tsx file and call it into my app.js file?

Here’s the error I am currently receiving. Am I missing the export on the Accordian code?

Module not found: Error: Can't resolve './components/Faq' in '/Users/rodriguezmedia/Desktop/blended/src'


    import { Group, Avatar, Text, Accordion } from '@mantine/core';
import React from 'react';

const charactersList = [
  {
    image: 'https://img.icons8.com/clouds/256/000000/futurama-bender.png',
    label: 'Bender Bending Rodríguez',
    description: 'Fascinated with cooking, though has no sense of taste',
    content: "Bender Bending Rodríguez, (born September 4, 2996), designated Bending Unit 22, and commonly known as Bender, is a bending unit created by a division of MomCorp in Tijuana, Mexico, and his serial number is 2716057. His mugshot id number is 01473. He is Fry's best friend.",
  },

  {
    image: 'https://img.icons8.com/clouds/256/000000/futurama-mom.png',
    label: 'Carol Miller',
    description: 'One of the richest people on Earth',
    content: "Carol Miller (born January 30, 2880), better known as Mom, is the evil chief executive officer and shareholder of 99.7% of Momcorp, one of the largest industrial conglomerates in the universe and the source of most of Earth's robots. She is also one of the main antagonists of the Futurama series.",
  },
  {
    image: 'https://img.icons8.com/clouds/256/000000/homer-simpson.png',
    label: 'Homer Simpson',
    description: 'Overweight, lazy, and often ignorant',
    content: 'Homer Jay Simpson (born May 12) is the main protagonist and one of the five main characters of The Simpsons series(or show). He is the spouse of Marge Simpson and father of Bart, Lisa and Maggie Simpson.',
  },
  {
    image: 'https://img.icons8.com/clouds/256/000000/spongebob-squarepants.png',
    label: 'Spongebob Squarepants',
    description: 'Not just a sponge',
    content: 'SpongeBob is a childish and joyful sea sponge who lives in a pineapple with his pet snail Gary in the underwater city of Bikini Bottom. He works as a fry cook at the Krusty Krab, a job which he is exceptionally skilled at and enjoys thoroughly. ',
  },
]

interface AccordionLabelProps {
  label: string;
  image: string;
  description: string;
}

function AccordionLabel({ label, image, description }: AccordionLabelProps) {
  return (
    <Group noWrap>
      <Avatar src={image} radius="xl" size="lg" />
      <div>
        <Text>{label}</Text>
        <Text size="sm" color="dimmed" weight={400}>
          {description}
        </Text>
      </div>
    </Group>
  );
}

function Demo() {
  const items = charactersList.map((item) => (
    <Accordion.Item label={<AccordionLabel {...item} />} key={item.label}>
      <Text size="sm">{item.content}</Text>
    </Accordion.Item>
  ));

  return (
    <Accordion initialItem={-1} iconPosition="right">
      {items}
    </Accordion>
  );
}

How would I fix this camera mouse glitch in ThreeJS

I’ve been working with ThreeJS for a couple of days now and i’ve come across a problem that i’ve seen happen in other online games. When I turn my camera using the PointerLockControls, it makes the camera go to a previous or random rotation. How would I fix this?

Here is the code that I am using for the camera:

import {PointerLockControls} from "three/examples/jsm/controls/PointerLockControls";
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const controls = new PointerLockControls( camera, renderer.domElement );
document.addEventListener('click', () => {
    document.querySelector("#bg").requestPointerLock();
});

It looks like this: https://youtu.be/RjcVDSZSvfg

How do I fix this?

Liquid Script based on Conditional JQuery

Let’s suppose we have a dropdown toggle:

<label for="num-of-records">Rows per Page: </label>
<select name="num-of-records" id="num-of-records">
  <option value="" selected>default</option>
  <option value="25">25</option>
  <option value="50">50</option>
</select>

And we also have a liquid code:

{% include 'page' key: 'table' %}

For key, I have provide some options table,table25, and table50 for each dropdown options value.

I am new to liquid, but I want to create a jquery which select the key value based on the dropdown.

<script>
$.(this).append("{% include 'page' key: 'table"+ $.(#num-of-records).val()+"' %}"
</script>

So let’s say I choose option 25, so it will (maybe reopen the page) append liquid script of:

{% include 'page' key: 'table25' %}

JQuery Datatables Ajax Datasource Error – Requested unknown parameter

I’m pretty stuck as to why I’m receiving this error from JQuery Datatables “DataTables warning: table id=myTable – Requested unknown parameter ‘0’ for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4″. I’ve tried to review the website info but it didn’t make much sense to me. My only guess is that it has something to do with the way the data may be formatted. If so, I’m unsure how to resolve the issue.

This chunk of code is getting the API so I can view it in the console and then again for the datatable data.

      var apiKey = "0ca80ddc-63f6-476e-b548-e5fb0934fc4b";
      $.ajax({
          type: "GET",
          url: "http://brew-roster-svc.us-e2.cloudhub.io/api/teams",
          headers: { "api-key": apiKey },
          success: function(result){
            console.log(result)
            console.log(JSON.stringify(result));
          }
      });
      $(document).ready( function () {
        $('#myTable').dataTable({          
          "ajax": {
            "url": "http://brew-roster-svc.us-e2.cloudhub.io/api/teams",
            "type": "get",
            "dataSrc": "",
            "beforeSend": function (request) {
              request.setRequestHeader("api-key", apiKey);
            },
            "columns": [
              { "data": "logo" },
              { "data": "name" },
              { "data": "league" },
              { "data": "division" },
            ],
          }
        });
      });

Here are the results from my debugging Ajax results in the console.

(30) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

This portion is a snippet of what I see when expanded:

0: {id: 133, nickname: 'Athletics', name: 'Oakland Athletics', location: 'Oakland', abbreviation: 'OAK', …}
1: {id: 134, nickname: 'Pirates', name: 'Pittsburgh Pirates', location: 'Pittsburgh', abbreviation: 'PIT', …}
[[Prototype]]: Array(0)