How to detect and track object changes in JS?

I want to keep an history of changes made to an entity. For example, user entity:

{
  name: 'Raz',
  places_visited: [
    { city: 'Jerusalem', street: 'King David', house_number: 10 }
  ]
}

Then these kind of changes may apply:

  1. name ‘Raz’ has updated to ‘Raziel’
  2. The first place he visited has updated from house_number 10 to house_number 20
  3. A new place has been inserted on top (he visited this place before the place that already in, like unshift): { city: 'Tel Aviv', street: 'Ibn Gabirol', house_number: 30 }

I want to store those changes somehow, probably in the DB in a dedicated History collection that will store just any changes, regardless the user entity. The history collection may look like this and have these fields:

EntityType, EntityId, KeyChanged, OldValue, NewValue, …(IAT and By and etc)

So in our case, the history collection should contain the next 3 rows:

  1. user, 123, name, Raz, Raziel, today, by admin
  2. user, 123, places_visited.0.house_number, 10, 20, today, by admin
  3. user, 123, places_visited.0, { city: 'Jerusalem', street: 'King David', house_number: 20 }, { city: 'Tel Aviv', street: 'Ibn Gabiron', house_number: 30 }, today, by admin,
  4. user, 123, places_visited.1, undefined, { city: 'Jerusalem', street: 'King David', house_number: 20 }, today, by admin

I have tried to use the JS new built in Proxy class:

const handler = {
  prefix: '',
  get(target, prop) {
    if (typeof target[prop] === "object" && target[prop] !== null) {
      handler.prefix += `${prop}.`
      return new Proxy(target[prop], handler)
    }
    return target[prop]
  },
  set(target, prop, newValue) {
    const oldValue = target[prop]
    target[prop] = newValue
    if (oldValue !== newValue) {
      console.log(oldValue, newValue)
    }
    return true
  }
}

const proxy = new Proxy(user, handler)

However, when using methods like push, unshift or so, are getting messy and the tracking is getting ruined.

How this can be achieved?

How can I animate a hidden card to appear

I have a set of MUI cards. One of these cards is hidden until the other cards are expanded. When the cards expand, the hidden card then appears. I want to animate the hidden card so that it does not suddenly pop in.

**  Styling **
summaryBox: {
    display: "flex",
},
qCard: {
    backgroundColor: "#D9F5FD",
    border: "1px solid #E1E1E1",
    width: "5vw",
    height: "auto",
    marginRight: "1vw",
},
...

const [expanded, setExpanded] = useState(false);
const [hidden, setHidden] = useState(true);
const handleExpandClick = () => {
    setExpanded(!expanded);
    setHidden(!hidden);
};

...
<Box className={classes.summaryBox} onClick={handleExpandClick} aria-expanded={expanded}>
    <Card className={classes.qCard} hidden={hidden}>
        <Collapse in={expanded} timeout="auto" unmountOnExit>
        </Collapse>
    </Card>
</Box>

avoid function call when change page without changes in states in react

i have this code:

import React, { useEffect, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import useAuth from "../../hooks/useAuth";
import { getTopicsbyDcentro } from '../../slices/topicsSlice';
import CorpusNameCard from "./CorpusNameCard";
import { getAccessTokenApi } from "../../api/auth";
import { setToken } from "../../slices/userSlice";

const CorpusNameFit = () => {   
 
  const dispatch = useDispatch();
  const accessToken = getAccessTokenApi();  
  dispatch(setToken(accessToken));
    
  const { user } = useAuth();
  const {
    responsable,
    editor,
  } = user;   
 
  const uniqueDCentros = Array.from(new Set(JSON.parse(responsable).concat(JSON.parse(editor))));    
  const getTopics = useSelector((state)=> state.topics.userTopics);   
  console.log(getTopics);
  const topics = Array.from(new Set(getTopics.map((topic)=> [topic.topicName, topic.workspace_id]))); 
  console.log(topics);
  const initFetch = useCallback(() => { 
    for (let dc of uniqueDCentros) {
      dispatch(getTopicsbyDcentro(dc));                   
    }
          
  }, [dispatch]);    
    
  useEffect(() => {
    console.log('useEffect');
    initFetch();  
  }, [user] ); 
  

  if (getTopics === undefined) return null;
  return (
    <div className="container" >
      <div className="subheader-bar">
        <h1 className="subheader-bar__title">Gestión del conocimiento</h1>
        <p className="subheader-bar__info">Estas son las temáticas que tienes asociadas a tu usuario. Selecciona la que quieras consultar.</p>
      </div>       
      <div className="row row-cols-1 justify-content-center row-cols-md-3 g-4 mt-5 mb-5">
        {topics && topics.map(title => <CorpusNameCard key={title} topic={title[0]} workspace_id={title[1]}/>)}        
      </div>
    </div>    
        
  );
};

export default CorpusNameFit;

When i click in navbar ‘Corpus de Conocimiento’ this code works.
When i am in the next page if i click again in the navbar ‘Corpus de Conocimiento’, to comeback to choose other option, the code works again, and the screen show the items duplicates. Because in the slice i have a array.push to store some values.

This is the slice:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import TopicsService from '../services/topics.service';

const initialState = {
  userTopics: [],
  selectTopic: '',
 
};

export const getTopicsbyDcentro = createAsyncThunk (
  "topics/get",
  async (dcentroId) => {        
    const res = await TopicsService.getTopics(dcentroId); 
    return res.data;
  }
);

const topicsSlice = createSlice({
  name: 'topics',
  initialState, 
  reducers: {
    setTopic: (state, action) => {
      console.log(action.payload);      
      state.selectTopic = action.payload;
    }
    
  },
  extraReducers: {
    [getTopicsbyDcentro.fulfilled]: (state, action) => {
      //state.userTopics = initialState;
      state.userTopics.push(...action.payload);
    },        
  }});

export const { setTopic } = topicsSlice.actions;

const { reducer } = topicsSlice;
export default reducer;

The thing is, if i comeback, my array push and push and push, but if i refresh the page, start from the begining and only store the first call in the array.

I don’t know if the issue is in the slice, that need check the data before push, or the usseffect that avoid recall the function if nothing has changed.

Thanks for your light

Form submit does not close the form and reload to the homepage

I have a problem setting up a form on my website.
I want to add two separate forms on my website, which i did, using some HTML & css.
Thoses forms need to send informations to a webhook -> it also works (since it’s collected)
BUT as soon as i press submit, it redirect to the main page of the website, so no conversion (which is a shame) and a very bad input from me.
Please, lend me your intelligence, since i must be the best idiot there is.

<form name='myForm' data-form-id='IdFromWebhook' action='WebhookLink' method='post' onsubmit="return false">
<div class="row">
  <div class="col-lg-12">
     <div class="form-group text_box">
        <label for='EMAIL_ADDRESS'>E-mail: </label><input id='insightly_email' name='email' type='text' required>
     </div>
  </div>
    <div class="col-lg-6">
     <div class="form-group text_box">
            <label for='FIRST_NAME'>First name: </label><input id='insightly_firstName' name='firstName' type='text' required>
     </div>
  </div>
    <div class="col-lg-6">
     <div class="form-group text_box">
            <label for='LAST_NAME'>Last Name: </label><input id='insightly_lastName' name='lastName' type='text' required>
     </div>
  </div>
  
    <div class="col-lg-4">
     <div class="form-group text_box">
<label for='Language__c'>Choose a language: </label>
<select id='insightly_language' name='language' required><option value='EN'>EN</option><option value='FR'>FR</option><option value='DE'>DE</option></select>
     </div>
  </div>
</div>
<!--Bouton d'envoi-->
<div style="display:flex;justify-content:center"><input class="btn_three" type='submit' value='Submit'></div></form>

How to await an async function in the constructor in JavaScript

I’m writing a JS class, which calls wasmFunc in the constructor and saves its result to this.val. However, because wasmFunc is from a WebAssembly file, an async function loadWasm must be called before wasmFunc is callable. So I’m trying to achieve something like this:

// index.js
async loadWasm() {
   // load wasm file
}

export class MyClass {
  constructor() {
    await loadWasm(); // Cannot work
    this.val = wasmFunc();
  }
}

export const myObj = new MyClass();

Ideally, this file index.js should export myObj that is ready for use. However, await cannot be used in the constructor.

Any solutions or thoughts?

dc.js rowchart Place of others not used

js a rowchart.
For hiding the “others” i use following:

chart.othersGrouper(null);

this hide the row others, but the place of this row is not used for the “normal” rows?
Is there an other way so that the normal rows can use the place od the other row?

Best way to avoid Cache Busting ( Need to Hard refresh ) in a react js web application?

i have a react js based web app the problem is every time there is a new deployment it needs to do hard refresh to see the change implemented which is very irritating to the client
i could see only two options to fix this

Client Side

Modifying external resources by appending some random stuff like "script.js?ts=timestring"

OR

Server Side

Using Web Pack to create a bundle and modifying the file name from server side by some random stuff

Now is there any other way to do this , also in client side solution i am trying to achieve this

by re appending the loaded scripts to the loading page in index.html

Array.from(document.querySelectorAll('script')).forEach(s => {
                 
                    var fileref = document.createElement('script');
                    fileref.setAttribute("type", "text/javascript");
                    fileref.setAttribute("src", s.src + "?ts=" + Date.now().toString());
                    document.getElementsByTagName("head")[0].appendChild(fileref);
                }  

but this solution is not working because appending the script again causing app to re-render resulting in blank page

please let me know what better can i do in both the cases , whether handle it client side of server side by webpack

How to store a user’s message as a variable in a Slack App? JS

I am quite new to working with Slack Apps and was stuck on this problem. I am writing a Slack App that needs to process a user message and pass it to an Amazon Lex Bot. I would like for when a user inputs a message into Slack for it to be stored in a variable userMessage. I was just wondering if there is any way to do this. Thanks!

AJAX (Response Undefined)

Previously I was a beginner in using AJAX, in this case I retrieve data from 2 different endpoints, data for phone number and token data. Previously I have managed to get the data. but I want to use custPhone and custToken data in the sso function, but when I execute it, the variable returns an undifined value, while in the console.log the data appears. maybe someone can help to use this variable so it doesn’t result in undefined

const button = document.getElementById('btn-submit');
button.addEventListener('click',function(){
  
  const email = document.getElementById('CustomerEmail').value; 
  
   function sso(url, custPhone, custToken, callback){
      var xhr = new XMLHttpRequest();
      xhr.open("POST", url);

      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.setRequestHeader("Authorization", `Bearer ${custToken}`);
      var data = `{
          "phone_number": ${custPhone},
          "countryCode": "ID",
          "programId": "4002203192624"
      }`;

      xhr.onreadystatechange = function () {
         if (xhr.readyState === 4) {
            console.log(xhr.status);
            const value3 = JSON.parse(xhr.response);
            const SSO = value3.url; 
            callback(SSO);
         }};


      xhr.send(data);
  }
  
  
  function getPhoneNumber(url, callback){
    // GET CUST DETAIL BY EMAIL
    const email = document.getElementById('CustomerEmail').value;

    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);

    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("X-Shopify-Access-Token", "shppa_8key");

    xhr.onreadystatechange = function(){
       if (xhr.readyState === 4) {
          const value1    = JSON.parse(xhr.response);
          const custPhone = value1.customers[0].phone;
          callback(custPhone);
       }};
  
    xhr.send();
  }
  
  
  
  function getTokenCust(url, callback){
      var xhr = new XMLHttpRequest();
    
      xhr.open("POST", url);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.setRequestHeader("Authorization", "Basic aWY5b0IwZHFZQTZzcHFpMGR3ajF0VnI3cTp2djhmRGJ5WTNVZHB6amtYSXd3dEZ2bVNUSkVKcE5scHp4VjJpUWxrbWt4VzJ3VTlzRg==");

      xhr.onreadystatechange = function () {
         if (xhr.readyState === 4) {
            const value2 = JSON.parse(xhr.response);
            const custToken = value2.access_token;
            callback(custToken);
            
         }};

      var data = `{
        "username": "98080001",
        "password": "0001",
        "grant_type": "password",
        "scope": "offline_access"
      }`;

      xhr.send(data);
  }
  
  
  getPhoneNumber(`https://zone-group-store.myshopify.com/admin/api/2021-07/customers/search.json?query=email:${email}`, function(custPhone){
    getTokenCust('https://api.gift.id/v1/pos/token', function(custToken){
      sso('https://api.gift.id/v1/pos/sso/wallet', custPhone, custToken, function(sso){
          alert(sso);
      });
    });
  });

How to group timestamp column in 1 minute bucket using Javascript

I have stored the table data in a data frame using Javascript. Now I want to group my data into 1 minute timebucket and get the latest record from that one minute timebucket using javascript. I have installed node-timebucket for this but not getting how to use it to apply it on dataframe that I have created.

https://github.com/carlos8f/node-timebucket

My code
module.exports = async function (context, req) {

const KustoClient = require("azure-kusto-data").Client;
const KustoConnectionStringBuilder = require("azure-kusto-data").KustoConnectionStringBuilder;

const kcsb = KustoConnectionStringBuilder.withAzLoginIdentity(`https://clustername.kusto.azuresynapse.net`); // optionally also pass authorityId
const client = new KustoClient(kcsb);

const results = await client.execute("db", "tbl | limit 10");
//console.log(JSON.stringify(results));
//console.log(results.primaryResults[0].toString());


const obj1 = results.primaryResults[0].toString();
const obj2 = JSON.parse(obj1);
x = obj2.data;
console.log(x);


var DataFrame = require('dataframe-js').DataFrame;
const df = new DataFrame(x);
df.select('timeSeries', 'value','timestamp','scaled_value');
df.show(20);


var timebucket = require('timebucket');

}

React – How to build a custom data grid/pivot table in React?

I have been trying to build a custom data grid/pivot table in React but unable to understand now to nest the data properly or recursively call the next data to do so. Following images show how the table would work:

As it can be seen from the images in the links, the entire table works on a hierarchical basis the the way data is stored in the db is tabular itself.

Eg.
| Local Group | Galaxy | Solar System | Planet | Location | Population |

  1. groupA g1 ss1 p1 america 10
  2. groupA g2 ss2 p2 india 15
  3. groupB g3 ss3 p3 sgp 4
  4. groupB g3 ss3 p4 dubai 11
  5. groupB g3 ss4 p5 uk 13
  6. groupB g4 ss5 p6 netherlands 16

Basically, there can be multiple local groups and each local group can contain multiple galaxies which can further contain multiple solar systems. Each solar system can then contain multiple planets which can contain multiple locations. Each location has a population.

I need a table to be able to group these up on the basis of columns as shows in the images.
Currently what I’ve tried is building a nested data but the level of nesting for 5 columns in way too much complexity.

How to amalgamate an array of Nodelists into a single array

I have a function that takes elements from the DOM to update a db on button click. Currently, there is one id for one value…

 <input class='total' doc-id='12345678' value='${whateverCurrent.value}'>user updates</field>
 <input class='total' doc-id='87654321' value='${whateverCurrent.value}'>user updates</field>

This is the function:

const elements = document.querySelectorAll('.total')
await Promise.all(Array.from(elements).map(async (el) => {
        let docId = el.id;
        let total = el.value;
        await updateDoc(docId, { total });
    }))
   

I now need to break this down such that there are 4 classes of input fields rather than 1 (by quarter). So there will be different elements but with the same id:

<input class='q1' doc-id='12345678' value='${whateverCurrent.value}'>user updates</field>
<input class='q2' doc-id='87654321' value='${whateverCurrent.value}'>user updates</field>
<input class='q2' doc-id='12345678' value='${whateverCurrent.value}'>user updates</field>

I could run the Promise.all function 4 times, once for each class, but that must be wrong, when instead I should somehow….

 // (do something here){
       await updateDoc(docId, {q1, q2, q3, q4})
 }

when I take all the elements and put them into an array and look at them in the console, I get an array of 4 NodeLists.

How do I take these 4 nodeLists and amalgamate them so that every id has its 4 values to pass to the update function?

Local storage set & get data showing in the DOM successfully working in chrome, but not working in Firefox

  1. This is my HTML container wrapper once page load I’m adding data into this.
```
<div class="container"></div>

```
    
  1. I’m dividing JS code into 2 part as sequence
``` 
    const getLocalStorage = JSON.parse(
            localStorage.getItem('storearrydata')
        );
            
            let persons = [
                {
                    id: 1,
                    fname: 'john',
                    birth: 'Jun 2018',
                    education: {
                        degree: 'MBA',
                        university: 'University 1'
                    }
                },
                {
                    id: 2,
                    fname: 'Singh',
                    birth: 'Aug 2020',
                    education: {
                        degree: 'MA',
                        university: 'University 2'
                    }
                },
                {
                    id: 3,
                    fname: 'Alia',
                    birth: 'Jan 2017',
                    education: {
                        degree: 'BA',
                        university: 'University 3'
                    }
                },
                {
                    id: 4,
                    fname: 'Deepika',
                    birth: 'Nov 2022',
                    education: {
                        degree: 'Art of School',
                        university: 'Patiala'
                    }
                },
                {
                    id: 5,
                    fname: 'Sunny',
                    birth: 'Dec 2021',
                    education: {
                        degree: 'Dancing',
                        university: 'New York'
                    }
                }

            ];

            persons = localStorage.getItem('storearrydata') !== null ? getLocalStorage : [];
            let containerEl = document.querySelector(".container");
    
```
  1. Second part of JS
```

function renderToDom(persons){
const markUp = persons.map((item) => {
return <ul> <li><span>Name:</span> ${item.fname}</li> <li><span>Birth:</span> ${item.birth}</li> <ul> <li><p>Education</p> <ul> <li><span>Degree:</span><span> ${item.education.degree}</span></li> <li><span>University:</span><span> ${item.education.university}</span></li> </ul> </li> </ul> <li><button onclick="removeItem(${item.id})" class="deleteItem">Delete</button></li> </ul>
}).join(”);

            containerEl.innerHTML  = markUp;  
        }

        
        renderToDom(persons);   
        
        
        function removeItem(id) {                   
            persons = persons.filter(currentId => currentId.id !== id);
            
            renderToDom(persons);  

            updateLocalStorage(); 
        } 

        function updateLocalStorage(){ 
            localStorage.setItem("storearrydata", JSON.stringify(persons));
        }


```

Transform datastructure with TypeScript

I would like to normalize and transform my data with TypeScript. The data that I get looks like this:

packages = {
  ungroupped: [
    {
      id: '0',
      status: 'active',
      owner: 'Stan Smith'
    },
    {
      id: '1',
      status: 'active',
      owner: 'Jill Smith'
    }
  ],
  groupped: [
    {
      name: 'Group 1',
      id: 1,
      accounts: [
        {
          id: '3',
          status: 'inactive',
          owner: 'Jane Smith'
        },
        {
          id: '4',
          status: 'hidden',
          owner: 'Stan Smith'
        }]
    }
   ]
};

What I would like to achieve, is this structure:

packages = [
  {
   name: null,
   id: null,
   accounts: [
     {
      id: '0',
      status: 'active',
      owner: 'Stan Smith'
     },
     {
      id: '1',
      status: 'active',
      owner: 'Jill Smith'
     }]
  },
  {
   name: 'Group XZY',
   id: 1,
   accounts: [
     {
      id: '3',
      status: 'inactive',
      owner: 'Jane Smith'
     },
     {
      id: '4',
      status: 'hidden',
      owner: 'Stan Smith'
     }]
  }
];

This is the code that I used to transform my data, but the result is not exactly what I want to have:

interface AccountGroupsUI {
   id: string;
   name: string;
   accounts: AccountUI[];
}

groups: AccountGroupsUI;

ngOnChanges(changes: SimpleChanges) {
  this.groups = [...this.packages.groupped];
  this.packages.ungroupped.map(data => {
    let newPackage = {
      id: null,
      name: null,
      accounts: this.packages.ungroupped
    };
    this.packages.push(newPackage);
  }
}

Now the code creates 2 “ungroupped” objects with the same content. I would like just one object with id: null, name: null, and all ungroupped account pushed into the accounts, but I cannot figure out how to do that. Can someone please help me?