How to refresh dataTable in ReactJS after the modal save button is clicked?

Hope you are Having a Good Day,

Can I ask for some help on how to refresh the dataTable in reactJs when I clicked the save button from the modal.

Here is my structure.

I have a parameterMaintenance.jsx below which imports the DataTable Component

ParameterMaintenance.jsx

import React from 'react'
import { ParameterDatable } from '../../components/ParameterDatatable'

export const ParameterMaintenance = () => {

  return (
    <div className='container mt-5'>
    <div></div>
    <ParameterDatatable/>
    </div>
  )
}

and then, I have a ParameterDataTable.jsx file that holds the dataTable.
notice that here, I called the AddParameter.jsx from the
DataTable actions property like this actions={<AddParameter/>}
to add a button that displays the modal form that handles the Saving of a new Parameter.

ParameterDatatable.jsx

import React, {useState, useEffect} from 'react'
import axios from 'axios';
import DataTable from 'react-data-table-component'; 
import DataTableExtensions from 'react-data-table-component-extensions';
import 'react-data-table-component-extensions/dist/index.css';
import "bootstrap/dist/js/bootstrap.bundle.js";
import "bootstrap/dist/css/bootstrap.css";
import { Link } from "react-router-dom";
import { AddParameter } from './AddParameter';

export const ParameterDatatable= () => {

    const [parameters, setParameters] = useState([]);
    
    useEffect(() => {
        loadParameters();
    }, []);

    
    const loadParameters = async () => {
        const result = await axios.get("http://localhost:8080/parameters");
        setParameters(result.data);
    };
    
    const deleteParam = async (id) => {
        await axios.delete(`http://localhost:8080/parameter/${id}`);
        loadParameters();
    };

    const column = [
        {
          name: "Param Name",
          selector: (row) => row.param_name,
          width: "180px" ,
          sortable: true,
          alignItems: 'center',
          display: 'flex',
        },
        {
          name: "Sequence Number",
          selector: (row) => row.param_sequence_number,
          width: "150px" ,
          sortable: true,
        },
        {
            name: "Parameter Value",
            selector: (row) => row.param_value,
            width: "150px" ,
            sortable: true,
        },
        {
            name: "",
            width: "110px" ,
            cell: row =>  
            <div className="App">
            <div className="openbtn text-center">
              <button
                type="button"
                class="btn btn-danger"
                data-bs-toggle="modal"
                data-bs-target="#myModal"
                
              >
                Delete
              </button>

              <div className="modal" tabindex="-1" id="myModal">
                <div className="modal-dialog">
                  <div className="modal-content">
                    <div className="modal-header">
                      <h5 className="modal-title">Danger</h5>
                      <button
                        type="button"
                        className="btn-close"
                        data-bs-dismiss="modal"
                        aria-label="Close"
                      ></button>
                    </div>
                    <div className="modal-body">
                      <p>Do you want to remove this record premanently?</p>
                    </div>
                    <div className="modal-footer">
                      <button
                        type="button"
                        className="btn btn-secondary"
                        data-bs-dismiss="modal"
                      >
                        Close
                      </button>
                      <button type="button" className="btn btn-primary" onClick={() => deleteParam(row.param_id)}
                      data-bs-dismiss="modal">
                        Yes
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
                ,
        },
        {
            name: "",
            width: "110px" ,
            cell: row =>  
                    <button
                    className="btn btn-primary mx-2"
                    onClick={() => deleteParam(row.param_id)}>
                      Edit
                </button>,
        },
      ]   
   
  return (
    <div className="datatable">
    <DataTableExtensions
    
    columns={column}
    data={parameters}
    print={false}
    export={false}
  >
    <DataTable 
        title="Parameters"
        columns={column} 
        data={parameters} 
        pagination
        fixedHeader
        fixedHeaderScrollHeight="450px"
        highlightOnHover
        actions={<AddParameter/>}
        
      subHeader

    />
    </DataTableExtensions>
    </div>
  )
}

create New

And below is my AddParameter.jsx which is the modal form for saving new parameter

AddParameter.jsx

import React, {useState} from 'react'
import axios from "axios";
import "bootstrap/dist/js/bootstrap.bundle.js";
import "bootstrap/dist/css/bootstrap.css";
import { Link, useNavigate } from "react-router-dom";

export const AddParameter = () => {

    let navigate = useNavigate();

    const [parameter, setParameter] = useState({
        param_name: "",
        param_sequence_number: "",
        param_value: "",
    });

    const {param_name, param_sequence_number, param_value} = parameter;

    const onInputChange = (e) => {
        setParameter({ ...parameter, [e.target.name]: e.target.value });
      };   

      const onSubmit = async (e) => {
        e.preventDefault();
        console.log("Submitting");
        await axios.post("http://localhost:8080/parameter", parameter);
        navigate('admin/parameter1');

      };   

  return (
    <div>
    <button className="btn btn-sm btn-info"
    data-bs-toggle="modal"
    data-bs-target="#exampleModal">Create New</button>
    <div className="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div className="modal-dialog">
      <div className="modal-content">
        <div className="modal-header">
          <h5 className="modal-title" id="exampleModalLabel">New Parameter</h5>
          <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div className="modal-body">
          <form onSubmit={(e) => onSubmit(e)}>
            <div className="mb-3">
              <label for="recipient-name" className="col-form-label">Parameter Name</label>
              <input type={"text"} className="form-control" placeholder="Param Name" name="param_name" value={param_name}
               onChange={(e) => onInputChange(e)}/>
            </div>
            <div className="mb-3">
              <label for="message-text" className="col-form-label">Sequence Number</label>
              <input type={"text"} className="form-control" placeholder="Sequence Number" name="param_sequence_number" value={param_sequence_number}
               onChange={(e) => onInputChange(e)}/>
            </div>
            <div className="mb-3">
              <label for="message-text" className="col-form-label">Parameter Value</label>
              <input type={"text"} className="form-control" placeholder="Value" name="param_value" value={param_value}
               onChange={(e) => onInputChange(e)}/>
            </div>
            <div className="modal-footer">
            <button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" className="btn btn-primary" data-bs-dismiss="modal">Save Parameter</button>
            </div>
        </form>
        </div>
      </div>
    </div>
  </div>
  </div>
  )
}

AddParameterModal

what I wanted to do is when I clicked the Save button, it will close the modal and refresh the DataTable, or call the loadParameters function which gets data from API in ParameterDataTable.jsx

Tried to use the navigate in reactjs to try to reload the page but the address will just add to the current address like this.
Navigate

anagrams can be handled with regexp

here is my requirement

const input = 'abcadbca';
const required = 'bca';

the input contains 3 possibility anagrams as:abc,bca,bca;
is this all can be selected using regexp?
i tried it, but got not result:

const str = 'abcadbca';
const reg = str.match(/(a|b|c)/g);

console.log(reg);

result expectation: [a,b,c,][b,c,a],[b,c,a];
result should be [a,b,c],[b,c,a] – first 2 match are overlapping so first match is taken for the account.

404 when trying to redirect to HTML Page

I’m trying to go from a JSX page to an HTML page, but I always get an error when I try to do so. Always a 404 page saying it doesn’t exist. It’s as if it doesn’t exist although I have it clearly in my files and in the same directory.

games.jsx

import React from "react";
import { useEffect, useState } from "react";
import moment from 'moment';
import Link from 'next/link';

export default function Home() {
    const[dataResponse, setdataResponse] = useState([]);
    useEffect(() => {
        async function getPageData() {
            const apiUrlEndpoint = 'http://localhost:3000/api/games';
            const response = await fetch(apiUrlEndpoint);
            const res = await response.json();
            console.log(res.games);
            setdataResponse(res.games);
        }
        getPageData();
    }, []);
    
    return (
        <div className='bg-gray-100 min-h-screen'>
            <a href="newgame.html">Click to Add New Game Product.</a>
            {dataResponse.map((games) => {
                var d = new Date(games.DateWhenAdded);
                var now = moment(d).format('l');
                return (
                    <div key= {games.ProductID}>
                        <div>{games.ProductName}</div>
                    <div>
                        <img src={games.ProductImage} width="400" height="400" alt=""/>
                    </div>
                        <div>
                            {games.ProductDescription}
                        </div>
                    <div>
                         Product added on: {now}
                    </div>
                    <div>
                        Product price: ${games.ProductPrice}
                    </div>
                </div>   
             )
            })}
    </div>
);
}

And this is the form I’m trying to redirect to. It’s called “newgame.html”

<!DOCTYPE html>
<html lang = "en">
<head>
<title>
New Game Addition
</title>
</head>
<body>
<form method="post" action="dbcon.php">
    <input type="number" name="ProductID" placeholder="Product ID">
    <input type="text" name="ProductName" placeholder="Name of Product.">
    <input type="text" name="ProductDescription" placeholder="Describe the Product.">
    <input type="file" name="ProductImage" placeholder="Put in Image">
    <input type="date" name="DateWhenAdded" placeholder="01/01/2001">
    <input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>

If you can give me any suggestions on what I should try, that would be greatly appreciated. Thank you.

disable entire section of checkboxes if a check box is clicked

I want to disable a section of checkboxes if the “not interested” check box is clicked. below is my code:

<div>
<input style="margin-left:30px" id="notInterest" type="checkbox" name="test" onclick="Reassign(this)"> Not Interested

</div>

<div class="form-group row" id="reassignChecks">
   @for (var i = 1; i <= 10; i++)

        {

            <input name="AreChecked" type="checkbox" value="@i" /> @i

            <br />

        }

        <button>Click</button>

            </div> 

I have the following JavaScript:

function Reassign(cb) {

            if (cb.checked == true) {

                document.getElementById('reassignChecks').disabled = true;

            } else {

                document.getElementById('reassignChecks').disabled = false;

            }

        }

if I click on “Not Interested” check box then I want to disable the entire section that has an ID of “reassignChecks”, but with the above JavaScript, this is not working. I dont want any of the checkboxes to be clicked in the reassignChecks section if Not Interested check box is clicked. below is the screen shot:

enter image description here

Cannot read properties of undefined only on refresh

While setting up a profile using firebase and react, I am getting the error of Cannot read properties of undefined: (reading 'name')
However, the strange part is that this doesn’t happen when I save my changes but when I refresh the page. I am curious, why is this happening?

Here is after I refresh the localhost:
Here is before refresh(when my work is saved):

Here is after I refresh the localhost:
Here is after I refresh the localhost:

Here is my current code:

  useEffect(() => {
    onAuthStateChanged(auth, async (user) => {
      if (user) {
        const snapshot = await getDoc(doc(db, "users", user.uid))
        console.log(snapshot.data().name)
        const userData= snapshot.data();
        
        setProfile(userData);

      } 
    });
  }, []);



  return (
    <>
      
      <Card>
        <Card.Body>
          <h2 className="text-center mb-4"> Profile</h2>
          <p className="details">
          {JSON.stringify(profile.name)}
          </p>
          {error && <Alert variant="danger">{error}</Alert>}
        </Card.Body>
      </Card>
      <div className="w-100 text-center mt-2">
        <Button variant="link" onClick={handleLogout}>
          {" "}
          Log out{" "}
        </Button>
      </div>
    </>
  );
};

For now, I’ll continue to just use JSON.stringify(profile) as that works fine but just was curious on this issue.

ask for geolocation permission again javascript

I had a website that would like to use your current location.:- speedometer

I am asking for permission on click ‘start’ btn.
I want that if it was denied I want to ask for permission on click btn.

 startBtn.addEventListener("click", function() {
 navigator.geolocation.watchPosition(
      function (e) {
        function ravi(e);
      },
      function (e) {
        errorEle.innerHTML = "ERROR(" + e.code + "): " + e.message;
      },
      { enableHighAccuracy: !0, maximumAge: 0 }
    );
});

ask for geolocation permission again if it was denied javascript

‘.’ is not recognized as an internal or external command, operable program or batch file with npm start — -e=stag -c=it

when i run the below command i am getting this error

command: npm start — -e=stag -c=it

error:

./scripts/start.js -e=stag -c=it

‘.’ is not recognized as an internal or external command,
operable program or batch file.

how can i solve this error

when i run the below command i am getting this error

command: npm start — -e=stag -c=it

error:

./scripts/start.js -e=stag -c=it

‘.’ is not recognized as an internal or external command,
operable program or batch file.

how can i solve this error

Javascript – use value from array for map icon colour

I’m creating a custom map using Apple MapKit JS and the data for the map icons and callouts is coming from an array. This is working well but all marker icons use the same colour. I’m using the Custom Callout example from the Apple website where it sets the value for the colour here:

    // Landmarks annotations
var annotations = sanFranciscoLandmarks.map(function(landmark) {
    var annotation = new mapkit.MarkerAnnotation(landmark.coordinate, {
        callout: landmarkAnnotationCallout,
        color: "#c969e0"
    });
    annotation.landmark = landmark;
    return annotation;
});

I’ve modified the array to include a markerColor value as well and was hoping I could reference that to specify the value for the marker icon colour:

    // Landmarks data
var sanFranciscoLandmarks = [
    { coordinate: new mapkit.Coordinate(37.7951315, -122.402986), title: "Transamerica Pyramid", phone: "+1-415-983-5420", url: "http://www.transamericapyramidcenter.com/", markerColor: "#c969e0"  },
    { coordinate: new mapkit.Coordinate(37.7954201, -122.39352), title: "Ferry Building", phone: "+1 (415) 983-8030", url: "http://www.ferrybuildingmarketplace.com", markerColor: "#FF0000" },
    { coordinate: new mapkit.Coordinate(37.7785538, -122.514035), title: "Cliff House", phone: "+1 (415) 386-3330", url: "http://www.cliffhouse.com/", markerColor: "#00FFFF" }
];

I’ve tried modifying this line:

 color: "#c969e0"

to:

 color: annotation.landmark.markerColor

which doesn’t work and generates a TypeError: undefined is not an object (evaluating 'annotation.landmark') in the browser console.

Is it possible to dynamically reference the marker colour from the markerColor value from the array?

state from switch component not updating

Description

I am currently creating multiple switch components in a table using React JS. I hope to be able to change the value of the state. However, when I click on a switch once, it will add a new object with a boolean value.

enter image description here

below screenshot showing overwriting value

enter image description here

Expected Results

My expectation is that when I click on a switch, it will directly change its state. Here’s the default state.
enter image description here

Code

Parent Code that handler event

 const [switches, setSwitches] = useState({
    lihat: false,
    tambah: false,
    hapus: false,
    ubah: false,
    view: false,
  });

  const handleSwitchChange = (event) => {
    const { id, checked } = event.target;
    setSwitches((prevActions) => {
      const newState = { ...prevActions, [id]: checked };
      console.log("newState:", newState);
      return newState;
    });
  };

...

 <FormCreateRole switches={switches} onChange={handleSwitchChange} />

Child Code

              **{row.slice(3).map((cell, idx) => {
                return (
                  <td key={idx}>
                    {row[2] &&
                      row[2].map((subIdx) => {
                        if (cell !== null) {
                          return (
                            <div key={subIdx} className="mb-3 text-center">
                              <Form.Check
                                type="switch"
                                id={`${subIdx}-${idx}`}
                                label=""
                                checked={switches[`action${idx}`]}
                                onChange={onChange}
                              />
                            </div>
                          );
                        }
                      })}**
                

Question

How to fix the issue and why is the event handler on the switch not changing the state?

Any help will be appreciated, Thank you.

Script to Convert Text to Font Enumeration for Indesign

I am attempting to expedite the process of coordinating fonts between translated comics (mainly CJK languages to English) in Adobe InDesign.

Beginning with a InDesign document in Language A, my company translates, typesets, and edits that comic in Language B. Eventually the initial document is totally scraped and its links are moved to a new document in a different arrangement (this is a reason behind my odd mission, but not super necessary to consider here). For all word balloons set in Font X in Language A, we want the corresponding balloons to be consistently set in Font X-Prime (a vibes-based equivalent) in Language B and sometimes C etc. Coordinating this between all parties working on a book is complicated, especially given that which fonts correspond between the two languages may change during the editing process.

To make this easier, editors often manually maintain ‘font bibles’ — documents which show screen shot examples of a font in Language A and note which font it corresponds to. The final aim here is to create a more efficient means of crafting these font bibles and to make it easier to check that a book is accurate.

As for the actual step which is creating an issue: I want to create a script which, for each font, finds all text frames set in that font, and replaces their contents with a unique number corresponding to that font. The converted document would then be an easy and scalable way to check for matches between many languages (eg. by listing that Meiryo:1:Helvetica etc). Below is a mock up of the goal, where different shapes represent different fonts in Language A (forgive it being an ms paint doodle, can’t share confidential works in progress).

A mock up depicting text in various fonts, represented by shapes, being converted to numbers which represent the font

This can be accomplished by just manually making find and replace changes, but it that is rather tedious. At first, automating this seem relatively attainable even with my meager scripting skills, but every method I tried was not successful, frequently for reasons which are unclear to me.

Here is the script that is closest to being successful so far. The final alert would output to a file in a completed version. This code was intended to loop through all fonts in the document, and for each one, replace every block of text set in that font with the index of the font. Instead, on my test file, the code successfully enumerates through each of 25 fonts, says that it finds zero text for 24 of them, and successfully replaces only 1 of the fonts with its number. The issue might somehow be with the font styles, because the only font it is successful with has no style. But I have not been able to figure out a way to fix it based on that.

It may also be significant that many of the fonts in the documents this script will run on are broken links (we don’t always have all the CJK fonts used by our licensors), but manual find and replace can work just fine with fonts like that.

We also can’t use character or paragraph styles instead of fonts, as the original files have none.

var document = app.activeDocument;
var fonts = document.fonts;
var list = "FONTS: n"

app.changeGrepPreferences.appliedFont = "Futura";
app.changeGrepPreferences.fontStyle = "Bold";
app.changeGrepPreferences.justification = Justification.CENTER_ALIGN;
app.findGrepPreferences.findWhat = NothingEnum.nothing;

for (index = 0; index < fonts.length; index++) {
                app.findGrepPreferences = NothingEnum.nothing;
                app.changeGrepPreferences.changeTo = index.toString();
                app.findGrepPreferences.appliedFont = fonts[index];
                list = list + app.changeGrepPreferences.changeTo +" : "+ app.findGrepPreferences.appliedFont.toString() + "n";
                alert(app.changeGrepPreferences.changeTo + " : " + app.findGrepPreferences.appliedFont.toString() + " : " + document.changeGrep().length.toString());
                try { document.changeGrep(); } catch (e) { alert("error"); }
}

alert(list);

I have also approached this by trying to loop through document.textFrames, but I gave up on that before seeing any progress, as I can’t figure out how to identify the font of the content in any given text frame.

Help is very much appreciated! This seemed like it would be an easy automation, but evidently there are not many other situations where text needs to be changed based on what font it is in, so I can’t find a good parallel to base my code on anywhere online. Thanks!

The size of pie chart dynamically fit in the collapsible section

I create a collapsible section. Click the collapsible button can toggle between showing and hiding a pie chart. I’m trying to make the chart size fit in the size of collapsible button dynamically.

The following javascript code can adjust the chart size dynamically when showing the chart.
However, in the hidden status of the collapsible section, if I firstly scale down the size of the collapsible button by adjusting the browser size, then open to show the pie chart. The pie chart will be firstly in its previous showing size (too large or too small).
The question is how to make the chart size fit to the size of collapsible button, even when the chart is hiding. Thanks!

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}

var config = {responsive: true};
let div_name = 'pie_chart0'
var data = [{
    values: [1, 2, 3],
    labels: ["A", "B", "C"],
    type: 'pie'
  }]
var layout = {
    autosize: true,
    title: {text: "pie chart"},
    style: { width: '100%', height: '100%' }
  }
Plotly.newPlot(div_name, data, layout, config);
/* Style the button that is used to open and close the collapsible content */
.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.active, .collapsible:hover {
  background-color: #ccc;
}

/* Style the collapsible content. Note: hidden by default */
#collapse_content {
  width: 100%;
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<button type="button" class="collapsible">collapsible button</button>
<div class="collapse_content" id="collapse_content">
  <div id="pie_chart0">
    <p>12345</p>
  </div>
</div>

Optimize the function to extract data from long string to and Object keys & values

I have a string that gets from the text file. In each line, it looks like this.

1=abc|2=TsMarketDataCache|3=1|4=141061|6=2023-02-27T05:04:50.472|36=F|7=1584A

The goal is to split the string by ‘|’ and get the key=value to the Object like this:

{
 '1': 'abc',
 '2': 'TsMarketDataCache',
 '3': '1',
 '4': '141061',
 ....
}

So I created a function in many ways that produce the same result.
My Solution:

// First approach (execution time around 1-2 seconds)
const translate = (msg) => {
  const keyValues = msg.split("|");
  const result = keyValues.reduce((acc, keyValue, index) => {
     const [key, value] = keyValue.split("=");
     const keyName = index + "_" + key;
     acc[keyName] = value;
     return acc;
  }, {});

  return result;
};

// Second approach (execution time around 5-6 seconds)
const translate = (msg) => {
  let index;
  let result = {};
  let acc = "";
  const len = msg.length;
  let c = 0;

  for (index = 0; index < len; index++) {
    if (msg[index] != "|") {
      acc += msg[index];
    } else {
      const [key, value] = acc.split("=");
      const keyName = (c++) + "_" + key;
      result[keyName] = value;
      
      acc = "";
    }
  }
  const [key, value] = acc.split("=");
  const keyName = c + "_" + key;
  result[keyName] = value;

  return result;
};

In the real case, the message data will be get from a text file that is around 3 million lines (very big).
So I just implement a code to test the execution time from the function above.
just loop 100000 times

// Just an example

let message = `1=Instrument%2@id%1'CHMOBI28C2303A_SYMB'%3|2=TsMarketDataCache|3=1|4=141061|6=2023-02-27T05:04:50.472|36=F|7=1584A|8=CHMOBI28C2303A_SYMB|9=SET_STOCK_DERIVATIVE_WARRANT_FOREIGN_UNDERLYING|10=T|11=T|12=0|13=CHMOBI28C2303A|14=SYMB|15=THB|16=CHMOBI28C2303A|17=SET|18=STOCK|19=DERIVATIVE_WARRANT_FOREIGN_UNDERLYING|20=700000|22=88138|23=1|24=100000000|25=F|27=372|28=1|31=2022-10-31|38=N/A|501=V|502=F|503=14000000|504=10000|531=F|506=F|507=F|508=F|509=3|510=3|525=700000|518=2023-02-24|522=T|51=F`;

console.time();
for (let i = 0; i < 100000; i++) {
  translate(message);
}
console.timeEnd();

the execution time of the first approach: 1-2 seconds

the execution time of the second approach: 5-6 seconds

It seems like the seconds approach uses Big O(n). I feel like it should be faster than the first one. I don’t know why?

Could someone explain?

Or if you find a better optimize solution it’d be great.

How to programmatically set the default color of all objects to no color or gray in Autodesk Platform Services v7 for progress tracking purposes?

I’m working with Autodesk Platform Services v7, and I’m trying to find a way to programmatically set the default color of all objects to either no color or gray. This is for the purpose of progress tracking in building construction, where users need to manually color objects that have completed construction.

The issue

I’ve searched through the official documentation, and while I did come across a method that allows me to change the color of selected objects, this doesn’t match my needs as I want to change the color of all objects at once.

https://aps.autodesk.com/en/docs/viewer/v7/reference/Viewing/Viewer3D/#setselectioncolor-color-selectiontype

Expected behavior

I’m looking for a code snippet that is able to automatically set the default color of all objects to either no color or gray.

Any help would be greatly appreciated.

Thank you in advance!