Replace table instead of append jquery

I have the following code segment that grabs user input from an HTML form, and then reads a CSV file, and grabs corresponding data to display to my website. If I submit another ‘searchTerm’ after the initial one in my form, it appends the new row of data from the csv file to the page, and I want it to replace instead. When I try to replace the row however, all my data vanishes.

function submitForm(){
    nameValue = document.getElementById("searchTerm").value;

    //document.getElementById("display-results").innerHTML = nameValue;
    location.href = "#page-3";

    function arrayToTable(tableData) {
        var table = $('<table></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            
            $(rowData).each(function (j, cellData) {
              if (cellData == nameValue) {
                row.append($('<td>'+rowData[1]+'</td>'));
              }
            });
            table.append(row);
        });
        return table;
    }

    $.ajax({
        type: "GET",
        url: "mainFile.csv",
        success: function (data) {
            parsed = Papa.parse(data).data;
            $('#display-results').append(arrayToTable(Papa.parse(data).data));
        }
    });
}

As you can see in the image, it appends the content rather than replacing the first array.

This is a simple example of how my code performs, it appends a new row of data instead of replacing the old one.

AWS Lambda fails when I import an image. Runtime.UserCodeSyntaxError

Context

I am working on a Lambda function in my index.js file to help me add watermark on images using Sharp.

This is the error I am getting.

2022-04-01T20:33:49.269Z    undefined   ERROR   Uncaught Exception  {"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Invalid or unexpected token","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Invalid or unexpected token","   
   at _loadUserApp ._loadUserApp (/var/runtime/UserFunction.js:200:13 undefined)","   
   at Object.module.exports.load (/var/runtime/UserFunction.js:242:17 undefined)","   
   at Object.<anonymous> (/var/runtime/index.js:43:30 undefined)","   
   at Module._compile (internal/modules/cjs/loader.js:1085:14 undefined)","   
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10 undefined)","   
   at Module.load (internal/modules/cjs/loader.js:950:32 undefined)","   
   at Function.Module._load (internal/modules/cjs/loader.js:790:12 undefined)","   
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12 undefined)","    at internal/main/run_main_module.js:17:47"]}

The Culprit

I realized the issue was happening when I imported a .png file.

const sharp = require('sharp');
const { S3 } = require('aws-sdk');
const stream = require('stream');
const playButtonPng = require('./assets/playButton.png'); // When this is commented out, the Lambda works

I thought about maybe “pulling” this image from S3, but it becomes complex since Sharp requires a “real image.”

So my question is: is it possible to import a local .png in a lambda function? I tried investigating but did not find any results.

Other Things I’ve tried:

  • Using CommonJS imports
  • Configuring Lambda to use Node 14.x as I am using v14.18.3 locally
  • Double checking syntax. Using Babel to compile.
  • Adjusting the sharp node_module for production. (I don’t think this was ever the issue).

I’ve also looked at these threads, which suggested

Arrow function that expects 2 numbers and returns undefined if they aren’t numbers

Need help. Need an arrow function that expects 2 numbers as input (e.g. 1, 2)
and returns the sum of the two numbers. If anything other than 2 numbers is passed, return undefined.
Not sure where I’m going wrong on this.

const sum = (num1, num2) => {
    
if((num1.value !== 0)||(num2.value !== 0)){
    return undefined
}
    return num1 + num2
}
console.log(sum(4,4))

Just keeps returning undefined, and doesn’t go to finding sum.

Blazor create WordCloud from a string

I have a Blazor Server .Net 6 app. I was looking to add a Word Cloud to my web page. I dont suppose anybody has built a Blazor component where I can pass it a string of words and it will generate a Word Cloud. I used High Charts years ago which did a nice job. But I cant seem to get it to work in Blazor

Its a nice to have so I cant justify buying a 3rd party component unfortunately

TIA

How to stop re-rendering of child component when its parent’s props change?

I have a Modal that is a child of a Card component:

Card > Modal

The Card has props that it sends down to the Modal. When I select an option in the Modal‘s UI, it updates the data in the Card and, thus, re-renders the Card, closing the Modal as it does so.

This is not ideal because I would like the user to continue to use the Modal until they explicitly hit “close”.

Is there a way to update the data/state in the underlying Card (so that the Modal can use the new state), but NOT trigger a full re-render of the component tree until the Modal is finally closed?

There is no Redux involved right now, and I’d like to avoid it if possible.

function with 2 arguments nad if statement [duplicate]

// FOR MODERATOR – I KNOW HOW TO LOWERCASE IT, I WANT TO DO SOMETHING ELSE

I’ve been styduing JS course and there is a function

function slugify(sentence, lowercase) {
    if (lowercase) {
      return sentence.replace(/s/g, '-').toLowercase();
    } else {
      return sentence.replace(/s/g, '-');
    }
  }

when I run it by

slugify('My name is Lucas') 

it works but I don’t know how to run it properly with the second argument to return this statement

sentence.replace(/s/g, '-').toLowercase();

I thought it was enough to put something in the second argument that returns true like

slugify('My name is Lucas', 1)

but it doesn’t work. It returns error:

js.js:44 Uncaught TypeError: sentence.replace(...).toLowercase is not a function
    at slugify (js.js:44:43)
    at <anonymous>:1:1

Please help.

Scoping and ‘this’ with Callbacks on a object [duplicate]

Why i am not able to access the method (addEvent) defined in the same object.

module.exports = {
    addEvent: (isBusy, res, evt) => {
        // some code ...
    },

    insertEvent: (evt, res) => {
        console.log(this.addEvent); // why?? undefined

        calendar.freebusy.query(
            {
                resource: {
                    timeMin: evt.start.dateTime,
                    timeMax: evt.end.dateTime,
                    items: [
                        {
                            id: 'primary',
                        },
                    ],
                },
            },
            (err, resp) => {
                if (err) return res.status(500).json({ error: 'Freebusy Error' + err });

                console.log(this.addEvent); // undefined

                this.addEvent(
                    resp.data.calendars?.primary?.busy.length !== 0,
                    res,
                    evt
                ); // Error:addEvent is not a function
            }
        );
    },
};

Note: Tried it with arrow functions too, but did not work.

Version

  • NodeJs v17
  • ExpressJs
  • Vscode

Angular provider receives JSON but recognizes its content as none

I have two components that depend on a third component function to receive some JSON data.
The function that them both use is this:

getAllPosting(before, after) {
    return new Promise((resolve, reject) => {
      console.log("url", environment.apiLogin + this.apiBase + localStorage.getItem('idEmpresa') + '/' + before  + '/' + after)
      this.http.get(environment.apiLogin + this.apiBase + localStorage.getItem('idEmpresa') + '/' + before  + '/' + after, {headers: {Authorization: this.oauthService.authorizationHeader()}})
        .subscribe((result: any) => {
**            console.log("provider result", result)**
            resolve(result);
          },
          (error) => {
            reject(error);
          });
    });
  }

On the first component, the highlighted console.log shows this result:

All the object fields and information is corret.

However, on the second component, the highlighted console.log shows this result:
The fields that we need, amountPaid and balace, keep coming as NaN

It’s does not seem to be a back-end problem since on the db all the data and the queries return the correct result. There are thousands of users but none of them have this problem, except for this current user.

This error is resulting to no data being show on the table, like:

The fields that should show on the table are the same fields that are coming back as Nan

I’ve tried requesting the data on different clients but none of them have this problem. It is exclusive of this one user.

Also, when trying to console.log the array using a forEach iteration, the corrent information is showing. However, when trying to console.log the whole object, the main fields that we use for the table keep showing as Nan.

result.forEach(element => {
              console.log("foreeach",element.amountPaid)
            });

enter image description here

How to check if object with some data is in array in javascript? [duplicate]

The programming language that I am currently using is vue.
I have some demo code right here:

<template>
  <button @click="checkInList">Check</button>
</template>

<script>
import { ref } from "@vue/reactivity";

export default {
  name: "App",
  setup() {
    const firstInput = ref("");
    const secondInput = ref("");
    const list = ref([
      { name: "lava", kind: "liquid" },
      { name: "air", kind: "gas" },
      { name: "water", kind: "liquid" },
      { name: "earth", kind: "object" },
    ]);
    const checkInList = () => {
      if (list.value.includes({ name: "lava", kind: "liquid" })) {
        console.log("array includes lava");
        // here I want to return the kind of that element, which will be liquid
      }
    };

    return {
      firstInput,
      secondInput,
      checkInList,
    };
  },
};
</script>

So how can I check if list contains the object with name lava and then return the kind of that object, which will be liquid?

How to fix my filtering for products in React

The task is to create a Fiter.jsx component that will filter Products.jsx (you can see it in the repository)

I have React Components :

Main.jsx

import React from "react";
import { Products } from "../Products";
import { Filter } from "../Filter";
import { Product } from "../Product";

class Main extends React.Component {
  state = {
    products: [],
    filteredProducts: [],
    status: "all",
  };

  onFilterStatusChange = (status) => {
    this.setState({ status });
  };

  componentDidMount() {
    fetch("./products.json")
      .then((responce) => responce.json())
      .then((data) => this.setState({ products: Object.values(data) }));
  }

  filterProducts() {
    this.setState(({ status }) => ({
      filteredProducts:
        status === "all"
          ? this.state.products
          : this.state.products.filter((n) => n.prod_status.includes(status)),
    }));
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.status !== prevState.status) {
      this.filterProducts();
    }
  }

  render() {
    // const { products } = this.state;

    return (
      <main className="container content">
        <Filter
          title="Status:"
          values={["all", "recommended", "saleout", "bestseller", "new"]}
          value={this.state.status}
          onChange={this.onFilterStatusChange}
        />
        <Products products={this.state.filteredProducts} />
      </main>
    );
  }
}

export { Main };

Filter.jsx

const Filter = ({ title, values, value, onChange }) => (
  <div>
    <h3>{title}</h3>
    {values.map((n) => (
      <label>
        <input
          type="radio"
          onChange={() => onChange(n)}
          checked={value === n}
        />
        {n}
      </label>
    ))}
  </div>
);

export { Filter };

At this stage, the console displays an error, and the site shows the following:

Question – help fix this…

Repo with all files

Before trying to create a filter, the site looked like this :

How to map complex json in React

I have an API that i am connecting to as part of an application that i am developing and i am having a hard time with trimming down everything to get to the objects and rendering out the data.

I have inserted some of the json snippet that is coming back from the API.

Please help.

[
  {
    "ssn": [],
    "name": [
      {
        "pidlist": [],
        "meta": {
          "sources": [],
          "firstSources": [],
          "middleSources": [],
          "lastSources": [],
          "firstInitialSources": [],
          "middleInitialSources": [],
          "firstSeen": 19931001,
          "lastSeen": 20220226,
          "count": 133,
          "rank": 0
        },
        "data": "JOHN R ARCHER",
        "first": "JOHN",
        "last": "ARCHER",
        "middle": "R"
      },
      {
        "pidlist": [],
        "meta": {
          "sources": [],
          "firstSources": [],
          "middleSources": [],
          "lastSources": [],
          "firstInitialSources": [],
          "middleInitialSources": [],
          "firstSeen": 19931001,
          "lastSeen": 20220222,
          "count": 79,
          "rank": 1
        },
        "data": "JOHN ROBERT ARCHER",
        "first": "JOHN",
        "last": "ARCHER",
        "middle": "ROBERT"
      },
      {
        "pidlist": [],
        "meta": {
          "sources": [],
          "firstSources": [],
          "middleSources": [],
          "lastSources": [],
          "firstInitialSources": [],
          "middleInitialSources": [],
          "firstSeen": 19870601,
          "lastSeen": 20211214,
          "count": 107,
          "rank": 2
        },
        "data": "JOHN ARCHER",
        "first": "JOHN",
        "last": "ARCHER"
      }
    ],
    "dob": [
      {
        "meta": {
          "sources": [],
          "dSources": [],
          "mSources": [],
          "ySources": [],
          "firstSeen": 19900301,
          "lastSeen": 20220222,
          "rank": 0
        },
        "date": {
          "data": "XX/XX/XXXX",
          "sortable": 0
        },
        "age": "51"
      },
      {
        "meta": {
          "sources": [],
          "dSources": [],
          "mSources": [],
          "ySources": [],
          "firstSeen": 19900301,
          "lastSeen": 20220222,
          "rank": 2
        },
        "age": "71"
      },
      {
        "meta": {
          "sources": [],
          "dSources": [],
          "mSources": [],
          "ySources": [],
          "firstSeen": 20070501,
          "lastSeen": 20070501,
          "rank": 3
        },
        "age": "??"
      }
    ],
    "address": [
      {
        "meta": {
          "sources": [],
          "firstSeen": 20151204,
          "lastSeen": 20220316,
          "count": 87,
          "rank": 0
        },
        "data": "1775 EDWIN DR, WAYLAND, MI 49348-9315",
        "streetNumber": "1775",
        "street": "EDWIN",
        "streetSuffix": "DR",
        "city": "WAYLAND",
        "state": "MI",
        "zip": "49348",
        "zip4": "9315",
        "dateRange": "12/04/2015-03/16/2022",
        "complete": "1775 EDWIN DR",
        "isCass": "Y",
        "county": "BARRY",
        "rank": 0,
        "latitude": 42.62675,
        "longitude": -85.534946,
        "ownership": "C",
        "topPoBox": 0,
        "highFrequency": false
      },
      {
        "meta": {
          "sources": [],
          "firstSeen": 20180816,
          "lastSeen": 20210629,
          "count": 3,
          "rank": 1
        },
        "data": "1803 S PATTERSON RD, WAYLAND, MI 49348-8817",
        "streetNumber": "1803",
        "street": "PATTERSON",
        "streetSuffix": "RD",
        "city": "WAYLAND",
        "state": "MI",
        "zip": "49348",
        "zip4": "8817",
        "predir": "S",
        "dateRange": "08/16/2018-06/29/2021",
        "complete": "1803 S PATTERSON RD",
        "isCass": "Y",
        "county": "BARRY",
        "rank": 1,
        "ownership": "C",
        "topPoBox": 0,
        "highFrequency": false
      },

This is what i have tried as a first step and cannot find anything helpful in searching:

  { Object.keys(data[0]).map((item, i) => (
            <div key={i}>
            </div>
    ))}

How to append an Image on two or more dom elements?

I’m finishing up my battleship project and want to add ship images. Before if a player places a ship at a certain coordinate, I just change the color of the divs as an indication of ship being placed. Now I want to place ( append ) images dynamically.

            <div class="gameBoard">
                <div class="grid"></div>
                <div class="grid"></div>
                <div class="grid"></div>
                <div class="grid"></div>
                <div class="grid"></div>
                <div class="grid"></div>
            </div>

The div gameboard above represents my board in the dom. And each divs represent each individual boxs where the players will attack each other. So how can I add one images on lets say to or more divs, so that the image span across those divs.

Expecting a Bool, Getting null

I have a function in a class

MyClass.prototype.IsFriend = function(){
    return (this.m_Object1 && !this.m_Object1.m_ABoolean && this.m_Object2);
};

m_Object1 is an object in MyClass.

m_ABoolean is a boolean within m_Object1, true or false.

m_Object2 is another object in MyClass.

When this function should be returning false when m_Object1 is null OR m_ABoolean is true OR m_Object2 is null, it returns null instead.

Note: m_Object1, m_ABoolean and m_Object2 are never undefined.

Why?

i was to make a blog application in typescript and react and i got this error in the application.tsx “Cannot find name ‘RouteComponentProps’.ts(2304)”

So I was making a blog application using typescript and Mern while I was routing the pages using the props, I got this error stating that

Cannot find name 'RouteComponentProps'

i have to search this error for a day now and I found out the version was an old version.. since I’m new to programming so I couldn’t modify the code according to the new version I have tried other methods like using for eg:

<Routes>
<Route path='/' element={<Homepage/>}/>
</Routes>

the above code works fine it displays the homepage at localhost:3000/ but the main problem I got over here as I was not able to get blogs/ID it was supposed to show the blogs page but I have an error in this and the other error I got was in the element in the application file

Below I have attached my snip-it

package.json

      "dependencies": {``
        "@testing-library/jest-dom": "^5.16.3",
        "@testing-library/react": "^12.1.4",
        "@testing-library/user-event": "^13.5.0",
        "@types/jest": "^27.4.1",
        "@types/node": "^16.11.26",
        "@types/react": "^17.0.43",
        "@types/react-dom": "^17.0.14",
        "react": "^17.0.2",
        "react-dom": "^17.0.2",
        "react-router-dom": "^6.2.2",
        "react-scripts": "5.0.0",
        "reactstrap": "^9.0.1",
        "typescript": "^4.6.3",
        "web-vitals": "^2.1.4"
      },
      

application.tsx

const Application: React.FunctionComponent<IApplicationProps> =
(props) => {
        return (
            <Routes>
              {routes.map((route, index) => {
                    return <Route path={route.path}  key={index} element={(routeProps: RouteComponentProps<any>) => <route.component
{...routeProps} />} />;
                })}

            </Routes>
           
        );
    };

    export default Application;