How can i add link in react material dynamic tables with API?

I’m using react material UI dynamic tables with props. Now I want to add a edit link in table cell, but not able to understand how can I do that?

My Code:-

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<script>
export const shippingAddressHeaders = [
  {
    title: 'Name',
    name: 'name',
    type: 'string'
  },
  {
    title: 'Address',
    name: 'addressLine1',
    type: 'string'
  },
  {
    title: 'Contact',
    name: 'contactNumber',
    type: 'string'
  },
  {
    title: 'Country',
    name: 'countryName',
    type: 'string'
  },
  {
    title: 'Actions',
    name: 'edit',
    type: 'string'
  }
];


 <Page className={classes.root} title={title}>
        <Container maxWidth={false}>
          <ViewHeader title={title} className={classes.content} />
          <div className={classes.content}>
            {shippingAddresses && (
              <>
                <CommonTableCtrl
                  className={classes.table}
                  isPagination={false}
                  headers={shippingAddressHeaders}
                  items={shippingAddresses}
                />
              </>
            )}
            {getForm(user.countryID)}
          </div>
        </Container>
        {toaster}
      </Page>
      
</script>

Thanks for your support!

How to put stars instead of 1-5

Hello how can i put stars instead of 1-5 here?
“` q.insertAdjacentHTML(‘beforeend’, <li class="starSubquestion"> <span class="starSubquestionName">Sub-question</span> <div class = "stars" id='colourRadioButtons'> </div>);
var element = document.getElementById(“colourRadioButtons”);
var newName = “colourRadioButtons” + subquestionNumber + “”;
element.id = newName;

    let lastRadio = false;

    const numbers = { "5": false, "4": false, "3": false, "2": false, "1": false, },
        radioStatic = {
            name: "colour"+questionNumber+""+subquestionNumber+"", onchange: (event) => {
                if (lastRadio) {
                    numbers[lastRadio] = false;
                }
                lastRadio = event.currentTarget.value;
                numbers[lastRadio] = event.currentTarget.checked;
            }, type: "radio"
        }; // radioStatic

    for (let key in numbers) {
        element.appendChild(
            Object.assign(document.createElement("label"), { textContent: key })).appendChild(
                Object.assign(document.createElement("input"), radioStatic, { checked: numbers[key], value: key }));
        if (numbers[key]) {
            lastRadio = key;
        }
    }
}

css:

    content: 'f005';
    transition: all .25s;
}

.stars{
    content: 'f005';
    color: white;
    transition: all .25s;
}

thank you for your time

Set kaboom.js background color after kaboom initialized

CODE: https://replit.com/@IMIBUKS/game#code/main.js:41:51

I am trying to make a simple infinite game in kaboom.js, however, i cant find anyway to change the background AFTER I DEFINED

main_init = kaboom({
  font: 'apl386',
  background: [97, 86, 240],
})

i tried main_init.color() but that did not work either.

  // increment score every frame
  onUpdate(() => {
    score++;
    hit_label.text = "H:" + fake_hits + "/10 S:" + score

    // Check for score
    if (score >= 1000) {
      main_init.color(129, 66, 245)
    }
  });

Second fetch in sequence of two doesn’t seem to have access to data returned from first fetch

I want to query a (django) server for an (RESTful) API schema, then use that schema for subsequent list and CRUD operations as may be defined therein. I’m using OpenAPI to autogenerate the schema, server-side. Trying to get a client-side API working was taking too long, so I switched to just using fetch instead.

The first fetch hits the endpoint that serves the API schema, and works fine.

The problem arises when I try to dereference a string within the returned schema in my second fetch call – this one to retrieve a list of “widget” objects from my server.

I found a way past this by simply assigning the string I needed to another const within the same function, then passing this to the second fetch.

This works, but I don’t understand why I need to do this to be able to use data from the first call. I’m able to reference it by console.logging it. I can see it using the browser’s debug console. But, for whatever reason, a reference to anything in the object returned by the first fetch becomes undefined in the second (or any subsequent?) fetch.

Can someone who understands javascript internals well explain this, or at least point me to something that can explain it? Thanks!

I’ve included code below that’s been somewhat sanitized. (I’m obviously not dealing with “widgets”.)

// given: a server hosting a "Widget" model, with an OpenAPI
//        RESTful API ...
// we want to retrieve a list of "Widget" objects via the "wigets"
// "list" API endpoint.
async function fetchApi_works() {

  // *** This part works ...
  const api = await fetch('http://localhost:8000/openapi/')
                           .then(r => r.json())
                           .catch(err => {
                                  console.log(err);
                               });
  console.log(api);                      // JSON data for API
  console.log(api.widgets.list.url);     // URL for retrieving list of stores
                                         // Note: NOT undefined

  const server = 'http://localhost:8000';

  // *** This does NOT work ... api.widgets.list.url appears to be undefined.
  const widgets1 = await fetch(server + api.widgets.list.url)
                        .then(r => r.json())
                        .catch(err => {
                            console.log(err.message);  // ** Comes here:  "undefined"
                        });
  
  // *** This works ...
  const widget_api = api.stores.list.url;  // This seems to be the difference.
   
  const widget = await fetch(server + widget_api)
                        .then(r => r.json())
                        .catch(err => {
                            console.log(err.message);
                        });
  console.log(widgets);
}

fetchApi_works();

filter higher order func explained

new here, Can someone help elaborate on this for me? I have been trying to understand why doesn’t “new” pop up in the return or the console log.

let words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present']
const appendedWords = words.filter( (word, index , arr) => {
  arr.push('new')
  return word.length < 7
})

console.log(appendedWords)

How to make a simple JS login with user in a predefined database?

I’m not sure how to go about this. I need to make a simple login that validate from a predefined database and displays a certain content in a div once logged in. Also, it needs to keep that data displayed in div until application is close. It is an NWJS app.

What I’ve come up with so far:

var checkLoginPass = function () {
    var login = document.getElementById("login").value;
    var pass = document.getElementById("password").value;
    if (login === "user123" && pass === "password1234") {
        window.location("http://www.google.com");
    }
    else {
        //do something else;
    }
};

<input type="text" id="login" required>
<input type="text" id="password" required>
<input type="button" id="goButton" onclick="checkLoginPass()" value="Log In"/>

Im still not exactly sure how to make it show content in a div after logged in or how to make a session like function to maintain “logged in status”

Flash message not showing in Reactjs

I am working on nextjs,I am integrating “newsletter”,Whenever my response is true
then validation message showing correct(if condition),but only show one time for 5 seconds,and whenever i am getting error then validation
message(else condition) not working,means “error” message not showing
Here is my code

import React, { useEffect, useState } from "react";
import FlashMessage from 'react-flash-message';
import { render } from 'react-dom';
const Subscribe = () => {
 const [email, setEmail] = useState('');
 const [error, setError] = useState('');
 const [success, setSuccess] = useState('');

const subscribeMe = async (event) => {
            
            const emails = email;
            event.preventDefault();
            
            const res = await fetch('https://example.com/admin-panel/Api/subscribe?email='+emails);
            const data = await res.json();
            const status = data["status"];
            const message = data["msg"];
            if (status === "false") {
                setError(error);
              } else {
                setSuccess(message);
              }
};
    const changeEmail = (event) => {
        const email = event.target.value;
        setEmail(email);
    }

And i tried with following code for display “success” or “error” message

{success && (
                    <FlashMessage duration={5000}>
                     <div class="alert alert-success">
                            <strong>{success}</strong>
                        </div> 
                    </FlashMessage>
                    
                )}          
                {error && (
                    <FlashMessage duration={5000}>
                     <div class="alert alert-danger">
                            <strong>{error}</strong>
                        </div> 
                    </FlashMessage>
                    
                )}  

Javascript callbacks not working as expected .? Want to know what is causing an error as such .?

    const  reConnectIfConnectionLost = (_vmSocket) => {
       
    try{
        console.log(_vmSocket)
        console.log(vmSocketConnectionStatus)
        
        if(vmSocketConnectionStatus == false){ 

            vmSocket = new W3CWebSocket('ws://34.*.*.*:*', 'echo-protocol');
            
        }
    }
    catch(err){
        console.log('Server must be offlice')
    }
    
}


setInterval( reConnectIfConnectionLost(vmSocket) , 10000 )

I’m getting the following error

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
at setInterval (node:timers:210:3)
at Object.

(C:UserschinnDocumentsTrialProjectswebSocketsForVMRaspPiClient.cjs:74:1)
at Module._compile (node:internal/modules/cjs/loader:1103:14)

at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)

at Module.load (node:internal/modules/cjs/loader:981:32)

at Function.Module._load (node:internal/modules/cjs/loader:822:12)

at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)

at node:internal/main/run_main_module:17:47 {
code: ‘ERR_INVALID_CALLBACK’
}

function reConnectIfConnectionLost(_vmSocket){
           
    try{
        console.log(_vmSocket)
        console.log(vmSocketConnectionStatus)
        
        if(vmSocketConnectionStatus == false){ 

            vmSocket = new W3CWebSocket('ws://*****', 'echo-protocol');
            
        }
    }
    catch(err){
        console.log('Server must be offlice')
    }
}
setInterval( reConnectIfConnectionLost(vmSocket) , 10000 )

I still get the same error ( I’m new to callbacks in Javascripts )

quill doesn’t see the event inside ‘text-change’

this.editor.on('text-change', function (delta, oldDelta, source) {
...someCode 
if(some condition) {
const range  = this.editor.getSelection()}}

but i can see this error Cannot read properties of undefined (reading ‘getSelection’)

this.editor equals quill and i can use this instead of quill, it’s worked in other function

How to see unremoved event listeners?

I am building a react project that requires a bunch of event listeners. I am removing the listeners as the components unmount, but I want to double check whether they are properly removed or not.

Are unremoved event listeners stacked together somewhere or are we unable to see them? I have searched the web and all I found were:

  1. getEventListener(${target_element});
  2. chrome devtools -> elements tab -> Event Listeners
  3. chrome devtools -> sources tab -> Event Listener Breakpoints -> fire my event

None of them seems to display the unremoved listeners being stacked. I want to see something like { click: Array(5) } as to show 5 duplicate listeners are dangling.

Build html form from xml with javascript

Here I’m again asking for help….

Let’s see, I’ve the next situation, I made a module for manage the clients in a web platform, when some register is gonna be created the user selects a client from a select and when a client is selected I make a request to get all the client data, one of these data is a XML string, which contains some structure (different for each client) and the user must fill some content in the nodes if the XML, for example, this is the XML structure for one client:

<?xml version="1.0"?>
<cfdi xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///c:/Users/dlucas/Desktop/Addendas%20XSD/Kuehne.xsd">
    <AD>
        <RECEPTION>
            <Tipo>
                <INVOICE>
                    <!--Element Purchase_Order is optional-->
                    <Order>string</Order>
                    <!--Element FileNumber_GL is optional-->
                    <GL>string</GL>
                    <Centre>string</Centre>
                    <Ref>string</Ref>
                </INVOICE>
            </Tipo>
        </RECEPTION>
    </AD>
</cfdi>

What I trying to do is that when the XML string is received process it and generate a HTML form with the XML tags (Order, GL, Centre and Ref) or all the tags inside the INVOICE tag… but this changes on every client’s XML.

I’ve been searching for some javascript library, but I believe it doesn’t not exist, not for convert the xml to a form… I found this project: http://www.datamech.com/XMLForm/ this is exactly what I need to do, and describes the structure of a XML and the types of Data Entry and Advanced Editing that this tool makes, I’ve tested this tool and works perfectly this the XML of this example, buy sadly this post doesn’t explain or gives some resource for made this work, that’s so sad!!

After this I tried to made it manually, but my ability to process and iterate the XML string is so poor (I know I’ve to practice more… and I’m on the way) but if someone could give me a hand to make this task I’ll be so grateful!

I’ve inspected the result os this tool, and this is the structure of the form:

 <div id="xmlForm">
        <form name="xmlForm" action="http://www.datamech.com/XMLForm/formXML0200.pl?.df=html" target="_blank" method="post">
          <div class="XMLcomplexContent">
            <fieldset class="cfdi">
              <legend>cfdi</legend>
              <input type="hidden" value="cfdi" name=".tg">
              <input type="hidden" name="@
                              xmlns:xsi" value="http://www.w3.org/2001/XMLSchema-instance">
              <input type="hidden" name="@xsi:noNamespaceSchemaLocation" value="file:///c:/Users/dlucas/Desktop/Addendas%20XSD/Kuehne.xsd">
              <div class="XMLcomplexContent">
                <fieldset class="Addenda">
                  <legend>Addenda</legend>
                  <input type="hidden" value="Addenda" name=".tg">
                  <div class="XMLcomplexContent">
                    <fieldset class="KNRECEPCION">
                      <legend>KNRECEPCION</legend>
                      <input type="hidden" value="KNRECEPCION" name=".tg">
                      <div class="XMLcomplexContent">
                        <fieldset class="Tipo">
                          <legend>Tipo</legend>
                          <input type="hidden" value="Tipo" name=".tg">
                          <div class="XMLcomplexContent">
                            <fieldset class="FacturasKN">
                              <legend>FacturasKN</legend>
                              <input type="hidden" value="FacturasKN" name=".tg">
                              <span class="XMLsimpleType">
                                <span class="Purchase_Order">
                                  <label>Purchase_Order: </label>
                                  <input type="text" class="Purchase_Order" name="Purchase_Order" value="string" onfocus="focusGained(this)" onchange="textChanged(this)">
                                </span>
                                <br>
                              </span>
                              <span class="XMLsimpleType">
                                <span class="FileNumber_GL">
                                  <label>FileNumber_GL: </label>
                                  <input type="text" class="FileNumber_GL" name="FileNumber_GL" value="string" onfocus="focusGained(this)" onchange="textChanged(this)">
                                </span>
                                <br>
                              </span>
                              <span class="XMLsimpleType">
                                <span class="Branch_Centre">
                                  <label>Branch_Centre: </label>
                                  <input type="text" class="Branch_Centre" name="Branch_Centre" value="string" onfocus="focusGained(this)" onchange="textChanged(this)">
                                </span>
                                <br>
                              </span>
                              <span class="XMLsimpleType">
                                <span class="TransportRef">
                                  <label>TransportRef: </label>
                                  <input type="text" class="TransportRef" name="TransportRef" value="string" onfocus="focusGained(this)" onchange="textChanged(this)">
                                </span>
                                <br>
                              </span>
                              <input type="hidden" value="/FacturasKN" name=".tg">
                            </fieldset>
                          </div>
                          <input type="hidden" value="/Tipo" name=".tg">
                        </fieldset>
                      </div>
                      <input type="hidden" value="/KNRECEPCION" name=".tg">
                    </fieldset>
                  </div>
                  <input type="hidden" value="/Addenda" name=".tg">
                </fieldset>
              </div>
              <input type="hidden" value="/cfdi" name=".tg">
            </fieldset>
          </div>
          <p>
            <input id="submit" type="submit" value="Generate XML">
            <input value="Reset" type="reset">
          </p>
        </form>
    </div>

And this is what it looks like on the browser:

enter image description here

Is important to say that when the user click in the save button the content of the form must be converted to a XML string but with the values that the user typed in the form…

I know this is a hard task, buy really I’ll appreciate some help, now I’m so confused, I’ll be working on this and if some progress is made I’ll communicate with yours…

Yelp Api business search not working in react native using axios – returns an empty array

Having trouble getting the yelp api to work, it is supposed to search for businesses based on the set of term. I am using a async await function to GET the businesses/search object, then I am setting my params then updating state using setResults


 import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import SearchBar from "../components/SearchBar";
import yelp from "../api/yelp";

const SearchScreen = () => {
const [term, setTerm] = useState("");
const [results, setResults] = useState([]);

console.log(results);
console.log(term);

const searchApi = async () => {
 try {
   const response = await yelp.get("/search", {
     params: {
       limit: 50,
       term,
       location: "san jose",
     },
   });
   setResults(response.data.businesses);
 } catch (err) {
   console.log(err);
 }
};

return (
 <View style={styles.background}>
   <SearchBar term={term} onTermChange={setTerm} onTermSubmit={searchApi} />
   <Text>We have found {results.length} results </Text>
 </View>
);
};

const styles = StyleSheet.create({});

export default SearchScreen;

Here is the SearchBar component

import React from "react";
import { View, TextInput, StyleSheet } from "react-native";
import { Feather } from "@expo/vector-icons";

const SearchBar = ({ term, onTermChange, onTermSubmit }) => {
  return (
    <View style={styles.backgroundStyle}>
      <Feather name="search" style={styles.iconStyle} />
      <TextInput
        autoCapitalize="none"
        autoCorrect={false}
        style={styles.inputStyle}
        placeholder="Search"
        value={term}
        onChangeText={onTermChange}
        onEndEditing={onTermSubmit}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  backgroundStyle: {
    backgroundColor: "#FFF",
    height: 50,
    borderRadius: 5,
    marginHorizontal: 15,
    top: 15,
    flexDirection: "row",
    marginBottom: 20
  },
  inputStyle: {
    flex: 1,
    borderRadius: 5,
    fontSize: 18,
  },
  iconStyle: {
    fontSize: 35,
    alignSelf: "center",
    marginHorizontal: 15,
  },
});

export default SearchBar;

And here is where I used axios to set the baseUrl and header

import axios from "axios";

export default axios.create({
  baseURL: "https://api.yelp.com/v3/businesses",
  headers: {
    Authorization:
      "BearerZPzXkPFyF_mWgHVjj_a1QZqiFkktt_iXYcX8JED6Gp2i73aYJTsvfUSApIVh7w8B8CNYfwnvBKo50MZvR34dvO3Cm1tQxlFp_PnGgCFjce1h0I1UF3zcKHnr7eq8YnYx",
  },
});

Any Help is greatly appreciated I console.logged the results and term to make sure all my state is working and it is so it has to be some issue with how i’m getting the yelp api. My results always return an empty array.

How to scrollIntoView only on initial render?

I am struggling to scroll the node into view only on initial render.
Here is what I am trying to do.

const [lastItemRef, setLastItemRef] = useState(null);
const [isScrolled, setIsScrolled] = useState(false);



useEffect(() => {
    if (lastItemRef !== null && !isScrolled) {
      lastItemRef.scrollIntoView({
        block: 'end',
        inline: 'center',
      });

      setIsScrolled(true);
    }
  }, [lastItemRef, isScrolled]);


[![return (
   <SomeList>
     <DeepItem ref={lastItemRef} /> 
   </SomeList>
)][1]][1]

enter image description here

enter image description here

** Check the screens **
DeepItem is is mentioned in the screen and I need to scroll into its view only once on the initial render.The strange thing is that when I remove setIsScrolled(true); the scrollIntoView is working but also is working on subseqent renders when I am trying to scroll the list up and down or left and right.
As I can somehow imagine DOM interaction is not happenning because it’s waiting for the react to update the internal state and once it happens, isScrolled is already false.
In the second screen you can see the result without removing setIsScrolled(true).

F.Y.I. – I am using MUI Table with react-window FixedSizeList.