Promise pending issue in React [duplicate]

I try to receive from a helperUtils file, the value that i get in a function.
In this function first i call to backend to get some information (this works perfect), then with this value (is an array of data) i do somethings inside te function to return a new value.

When i call this function from my .jsx file and try to receive the final value, i receive Promise in my console when i do a console.log.

function inside Helperutils.js

export const getResponseId = async (idStart) => { 
  const res = await getResponsIdApiNew(idStart);  
  if (res.length === 0) {    
    return (idStart + "1");
  } else {    
    let numbersArray = [];
    for (let j = 0; j < res.length; j++) {      
      if (res[j].substring(idStart.length, res[j].length)[0] !== "") {            
        numbersArray.push(Number(res[j].slice(idStart.length, res[j].length)));           
      }
    }
    if (numbersArray.length !== 0) {         
      const max = Math.max(...numbersArray);              
      let exist = false;
      for (let i = 1; i <= max; i++) {           
        if (!res.includes(idStart + i)) {          
          exist = true;
          idStart = idStart + i;
          console.log(idStart); //give me the value that i want
          break;
        }
      }
      if (exist) {
        console.log(idStart); //give me the value that i want
        return (idStart);
      } else {
        let number = max + 1;
        console.log(idStart + number)     
        return (idStart + number);
      }
    }
  }  
};

in my file.jsx:

i did try:

const getNewIdResponse = async () => {
    await getResponseId(`${getTopic}_${typeResponseTitle}_`);
  };
  console.log(getNewIdResponse);

and try:

const getNewIdResponse = getResponseId(`${getTopic}_${typeResponseTitle}_`);
console.log(getNewIdResponse);

all consoles print:

enter image description here

How to parse JSON using pure JavaScript for simple login form which works on local storage?

I am trying to make simple login form using local storage but i am not able to load json file from https://www.sharestudy.in/internal/assets/usersV2.json.

Someone suggest me this way but failed …. please help..

var storeS = localStorage.getItem("users");
if(storeS==null){
  var users = JSON.parse(users);
    localStorage.setItem("users",JSON.stringify(users));
}
function getUserUsername(username) {
    return JSON.parse(localStorage.getItem('users')).filter(users => users.username === username)
}
<script type="text/javascript" src="https://www.sharestudy.in/internal/assets/usersV2.json"></script>

In which language is HTML parser written in?

Whenever i ask this question on google, i get the answer that “HTML is a markup language, its not written”, but there must be a binary code in browser whcih tells the computer things like “if you see a then display text inside it, give it a background and make it clickable”, and that binary may be written in a compiled or assembly language.

Where to add a key to dynamic tables in React?

Hi I use a search box made using React and Material UI/MUI that references a json file which has the tags id, firstname, lastname, address, city, zip. The search box searches the emails for matching the input characters. The matched values are rendered as a dynamic table that changes as more and more characters are typed. I have made edit buttons for each table row that loads but I am not able to successfully edit any entry. Upon using the console in Dev Tools in Chrome, I found a warning for each child to have a key in List.js but I tried using {key=item.id} in several locations like the Fragment tag and the EditableRow tag. Can I please get some ideas on this? Thanks in advance !!!

Here is my code

import TextField from "@mui/material/TextField";
import List from "./Components/List";
import "./App.css";

function App() {
  const [inputText, setInputText] = useState("");
  let inputHandler = (e) => {
    //convert input text to lower case
    var lowerCase = e.target.value.toLowerCase();
    setInputText(lowerCase);
  };

  return (
    <div className="main">
      <h1>Search</h1>
      <div className="search">
        <TextField
          id="outlined-basic"
          onChange={inputHandler}
          variant="outlined"
          fullWidth
          label="Search"
        />
      </div>
      <List input={inputText} />
    </div>
  );
}

export default App;

The App.js is the main wrapper for the search box, all the search logic and table rendering logic is found in List.js below (to be place in a Components folder in the same dir as the App.js file)

import data from "./ListData.json"
import ReadOnlyRow from "./ReadOnlyRow.js"
import EditableRow from "./EditableRow.js"

function List(props) {
    const [contacts, setContacts]=useState(data);
    const [editContactId, setEditContactId] = useState(null);
    const [editFormData, setEditFormData] = useState({
        CustomerLogonId: "",
        FirstName: "",
        LastName: "",
        Address: "",
        City: "",
        Zip: "",
      });

      const handleFormChange = (event) => {
        event.preventDefault();

        const fieldName = event.target.getAttribute("name");
        const fieldValue = event.target.value;

        const newFormData = {...editFormData};
        newFormData[fieldName] = fieldValue;

        setEditFormData(newFormData);
    };

    const handleFormSubmit = (event) => {
        event.preventDefault();
        const editedContact = {
            id : editContactId, 
            CustomerLogonId: editFormData.CustomerLogonId,
            FirstName: editFormData.FirstName,
            LastName: editFormData.LastName,
            Address: editFormData.Address,
            City: editFormData.City,
            Zip: editFormData.Zip
        }
        const newContacts = [...contacts];

        const index = contacts.findIndex((item) => item.id === editContactId)
        newContacts[index] = editedContact;
        setContacts(newContacts);
        setEditContactId(null);
    }
      const handleEditClick = (event, item) => {
        event.preventDefault();
        setEditContactId(item.id);
        const formValues = {
            CustomerLogonId: item.CustomerLogonId,
            FirstName: item.FirstName,
            LastName: item.LastName,
            Address: item.Address,
            City: item.City,
            Zip: item.Zip
        }
        setEditFormData(formValues);
    }

    const handleCancelClick = () => {
        setEditContactId(null);
      };

    //create a new array by filtering the original array
    const filteredData = data.filter((el) => {
        //if no input then return a empty string
        if (props.input === '') {
            return '';
        }
        //return the customer which contains the user input email id 
        else {
            return el.CustomerLogonId.toLowerCase().includes(props.input)
        }
    })
    return (
        <div className='app-container'>
            <form onSubmit={handleFormSubmit}>
            <table>
                <thead>
                    <tr>
                        <th>CustomerLogonId</th>
                        <th>FirstName</th> 
                        <th>LastName</th> 
                        <th>Address</th> 
                        <th>City</th>
                        <th>Zip</th>
                        <th>Actions</th>
                    </tr>
                </thead>

            <tbody>
                {filteredData.map((item) => (
                <Fragment>
                   {editContactId === item.id ? (<EditableRow key={item.id} editFormData={editFormData} handleFormChange={handleFormChange} handleCancelClick={handleCancelClick} />) : (<ReadOnlyRow key={item.id} item = {item} handleEditClick = {handleEditClick} />) } 
                </Fragment>
                
    ))}
            </tbody>

            </table>
            </form>
        </div>
    )

                }
export default List

Here are the ReadableRow and EditableRow files (which should be placed in the Components folder as well)

import React from "react";

const ReadOnlyRow = ({ item, handleEditClick }) => {
    return (
    <tr>
    <td>{item.CustomerLogonId}</td>
    <td>{item.FirstName}</td>
    <td>{item.LastName}</td>
    <td>{item.Address}</td>
    <td>{item.City}</td>
    <td>{item.Zip}</td>
    <td><button type="button" onClick={(event)=> handleEditClick(event,item)}>Edit</button></td>
    </tr>);
};

export default ReadOnlyRow;
import React from "react";

const EditableRow = ({ editFormData, handleFormChange, handleCancelClick  }) => {
    return (
    <tr>
    <td><input type="text" required="required" placeholder="Enter the email.." name="CustomerLogonId" value={editFormData.CustomerLogonId} onChange={handleFormChange}></input></td>
    <td><input type="text" required="required" placeholder="Enter the firstname.." name="FirstName" value={editFormData.FirstName} onChange={handleFormChange}></input></td>
    <td><input type="text" required="required" placeholder="Enter the lastname.." name="LastName" value={editFormData.LastName} onChange={handleFormChange}></input></td>
    <td><input type="text" required="required" placeholder="Enter the address.." name="Address" value={editFormData.Address} onChange={handleFormChange}></input></td>
    <td><input type="text" required="required" placeholder="Enter the city.." name="City" value={editFormData.City} onChange={handleFormChange}></input></td>
    <td><input type="text" required="required" placeholder="Enter the zip.." name="Zip" value={editFormData.Zip } onChange={handleFormChange}></input></td>
    <td><button type="submit">Save</button><button type = "button" onClick={handleCancelClick}>Cancel</button></td>
    </tr>);
};

export default EditableRow;

Here’s also the JSON file if you want to take a crack at this

[{
    "id": 1,
    "CustomerLogonId": "[email protected]",
    "FirstName": "Albert",
    "LastName" : "Lee",
    "Address" : "Street 1",
    "City" : "A",
    "Zip" : "000001" 
}, {
    "id": 2,
    "CustomerLogonId": "[email protected]",
    "FirstName": "Bertha",
    "LastName" : "Summers",
    "Address" : "Lane 2",
    "City" : "A",
    "Zip" : "000001" 
}, {
    "id": 3,
    "CustomerLogonId": "[email protected]",
    "FirstName": "Carl",
    "LastName" : "Johnson",
    "Address" : "Street 3",
    "City" : "B",
    "Zip" : "000001" 
}, {
    "id": 4,
    "CustomerLogonId": "[email protected]",
    "FirstName": "Duster",
    "LastName" : "Jones",
    "Address" : "Lane 4",
    "City" : "B",
    "Zip" : "000002" 
}, {
    "id": 5,
    "CustomerLogonId": "[email protected]",
    "FirstName": "Earl Jones",
    "LastName" : "Smith",
    "Address" : "Street 4",
    "City" : "B",
    "Zip" : "000003" 
}, {
    "id": 6,
    "CustomerLogonId": "[email protected]",
    "FirstName": "Felicia",
    "LastName" : "Hardy",
    "Address" : "Lane 5",
    "City" : "B",
    "Zip" : "000003" 
}, {
    "id": 7,
    "CustomerLogonId": "[email protected]",
    "FirstName": "George",
    "LastName" : "Harrison",
    "Address" : "Street 6",
    "City" : "C",
    "Zip" : "000004" 
}, {
    "id": 8,
    "CustomerLogonId": "[email protected]",
    "FirstName": "Harry",
    "LastName" : "Potter",
    "Address" : "Gryffindor House",
    "City" : "Hogwarts",
    "Zip" : "000934" 
}, {
    "id": 9,
    "CustomerLogonId": "[email protected]",
    "FirstName": "India",
    "LastName" : "Summers",
    "Address" : "Land 9",
    "City" : "A",
    "Zip" : "000005" 
}, {
    "id": 10,
    "CustomerLogonId": "[email protected]",
    "FirstName": "James",
    "LastName" : "Bond",
    "Address" : "Mi6",
    "City" : "B",
    "Zip" : "000005" 
},
{
    "id": 11,
    "CustomerLogonId": "[email protected]",
    "FirstName": "George",
    "LastName" : "Foreman",
    "Address" : "Street 6",
    "City" : "C",
    "Zip" : "000004" 
}] 

document.getElementById – Issue in making the text box readOnly and greyed out using java script

I have to decide between a situation involving Unicast and Multicast.

When I enable the check  box, I need to make sure the stream type I’ve selected is Unicast or Multicast.

if Multicast is being used, the checkbox should be left blank with empty  String.
         

if Unicast is being Used ,the current textbox should be made read-only and should be greyed out.

toggler = document.getElementsByName("currentEntry.enableCB");
 var srcIp = document.getElementById("sourceIp");
 var input_stream_type = document.getElementsByName("currentEntry.streamType")[0];
 if(toggler[0].checked ){
 
    if(input_stream_type.value === 'Multicast'){
                                
              srcIp.style.display = ''; //It shows the textbox with empty string so that we can fill in the data - Expected and working fine
    } else {
    
               //srcIp1.readOnly = true;
               //srcIp1.setAttribute("readOnly","true");
               srcip1.setAttribute('readOnly','readOnly'); //The text box should be read-only in this case and should be greyed out, yet all three options hide the textbox.
    }
 } else {
         srcip1.style.display = 'none'; //It hides the text box - expected and working fine
 }

Could someone shed some lights on how to display the textbox in read-only mode with greyed out mode when the Unicast option selected ?

Multiple nested select dropdown list dependent on input element in JavaScript

I have input element as range for years. I can change value of year by buttons. I would like to create nested list in second select that depends on year from range input and on first select – id countrySelect.

<input type="range" id="yearRange" min="0" max="3" list="yearsDatalist" value="3"
onChange="changeYear(value)" onInput="changeYearLite(value)">
    <datalist id="yearsDatalist">
        <option value="0" label="1918"></option>
        <option value="1" label="1936"></option>
        <option value="2" label="1950"></option>
        <option value="3" label="1981"></option>
    </datalist>

Then I have two select elements. The first one is static – not necessary to change the values there:

<select id="countrySelect">
    <option value="0">Sweden</option>
    <option value="1">Germany</option>
    <option value="2">USA</option>
</select>

Second select is dependent on year and on values in first select with id=moduleSelect

<select id="itemSelection"></select>

I used object for values like this in some different project:

const yearsFilterDataList = {
    "1918": {
        "0": "Choose model",
        "volvo": "Volvo",
        "mercedes": "Mercedes",
        "saab": "Saab"
    }, ...

Format JavaScript object by parentId

I have some data,

"results": [
        {
            "status": "Active",
            "id": "1",
            "parentId": 0,
            "title": "Study Abroad",
            "slug": "study-abroad",
            "link": "explore-university",
            "isMegaMenu": 1,
            "position": "1",
            "isGroup": 1,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "2",
            "parentId": 0,
            "title": "Exam Prep",
            "slug": "exam-prep",
            "link": "exams",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "3",
            "parentId": 0,
            "title": "Documents",
            "slug": "documents",
            "link": "documents",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "4",
            "parentId": 0,
            "title": "Adviser",
            "slug": "adviser",
            "link": "counsellors",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "5",
            "parentId": 0,
            "title": "Blog",
            "slug": "blog",
            "link": "blog",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "6",
            "parentId": 2,
            "title": "IELTS Guide",
            "slug": "ielts-guide",
            "link": "exam/ielts",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "7",
            "parentId": 2,
            "title": "PTE Guide",
            "slug": "pte-guide",
            "link": "exam/pte",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "8",
            "parentId": 3,
            "title": "SOP Guide",
            "slug": "sop-guide",
            "link": "document/sop",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "9",
            "parentId": 3,
            "title": "LOR Guide",
            "slug": "lor-guide",
            "link": "document/lor",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        },
        {
            "status": "Active",
            "id": "10",
            "parentId": 1,
            "title": "Study In Australia",
            "slug": "study-in-australia",
            "link": "_self",
            "isMegaMenu": 0,
            "position": "2",
            "isGroup": 0,
            "type": "Study",
            "target": "_self",
            "iconId": "0",
            "description": "This is first menu"
        }
    ]

I need to format the data by parentId. ParentId = 0 will be main data. And it will contain all chield data if the data contain parentId of that id.
Example object id 6 will be in the child data of object id 2. Object id 10 will be in object id 1 as it contain parentId 1. The nested have no limit.

why Dropdown is not working after ajax call?

I am using jquery code to make drop down on sidebar filters. this code is working properly but after selecting a filter this code is not working , i think due to ajax call. what is solution. please guide me

jQuery(function(){
    jQuery("#sidebar h4, #sidebar h3, body.woocommerce #sidebar>div>.inner .widget h4, body.woocommerce #sidebar>div>.inner .widget h3").on('click', function(){
        jQuery(this).parent().toggleClass("dropdown-hide");
    });
});

Can’t display webcam from another component

I’m trying to display my webcam image stream using the react-webcam library. The webcam displays fine when I load all the code in the App.js file directly, although when I try to create a new component for the webcam and use it in App.js using props, I get no output (blank white screen)

Test.js

export default function Test(props){



    return (
        <div className="App">
          <header className="App-header">
            <Webcam
            audio = {false}
            ref = {props.webcamRef}
            style = {{
              position: "absolute",
              marginLeft: "auto",
              marginRight: "auto",
              left: 0,
              right: 0,
              textAlign: "center",
              zIndex: 9,
              width: 640,
              height: 480,
            }}>
            </Webcam>
    
            <canvas
            ref = {props.canvasRef}
            style = {{
              position: "absolute",
              marginLeft: "auto",
              marginRight: "auto",
              left: 0,
              right: 0,
              textAlign: "center",
              zIndex: 9,
              width: 640,
              height: 480,
            }}>
    
            </canvas>
          </header>
        </div>
      );
}

App.js

function App() {
  const webcamRef = useRef(null);
  const canvasRef = useRef(null);
  <Test webcamRef = {webcamRef} canvasRef = {canvasRef}/>
}

export default App;

How do I fix this?
P.S. I’m a beginner in front end dev and react so please go easy on me if this is a stupid question

How to change the src of an image dynamically with media queries in css or sass

I have a responsive website created with bootstrap and sass. I load the background image in the home page dynamically using bootstrap break points in sass.

At the same page I have other images that load heavily. I have created a way to load images based on width such that <img src='assets/img/myImage?width=500'> so that I reduce the size based on the viewport. But I coulnd’t find a way to control the src of the img tag in sass file so that I use @media query and decide the width dynamically.

Any idea how to implement this?

are async/await async or synchronous?

I’m actually diving into the asyc/await part for the first time so I am having a hard time understanding it.

I know that async await is used to make a function run in an async manner but how, because as per the definition, the “await” keyword halts the execution of a function until the promise is resolved, and then executes the leftover code in the function. Isn’t this a synchronous behaviour, because things are getting executed in order as they should be?

Feel free to help me out of my confusion or if I am wrong somewhere.

How to structure often used functions

I recognised that in few different pages i am locating elements by the exact same locators, as an example i have created LoginInPage and RegistrationPage and both of them have static function emailInput() there are more elements i am locating by the exact locators and its values through the project, so my question what would be modern approach towards it?

I did research and saw that often used functions are placed in commands.ts but personally i do not like this approach as what if commands will end up having 30+ functions it be super messy, would appreciate any solutions suggested

export class LogInPage {
  static get emailInput(): Cypress.Chainable<JQuery<HTMLInputElement>> {
    return cy.get<HTMLInputElement>('input[placeholder="Email address"]');
  }
}


 export class RegistrationPage {
      static get emailInput(): Cypress.Chainable<JQuery<HTMLInputElement>> {
    return cy.get<HTMLInputElement>('input[placeholder="Email address"]');
  }

Axios error : TypeError: adapter is not a function

I’m making a web extension using webextension-polyfill and vuejs (axios for requesting).
I needed to make requests from my content script but it threw my cors errors, so I forwarded thoses requests to the background script. But axios thew me that error :
axios error

here’s my manifest :

{
    "manifest_version": 3,
    "name": "Teamlock web extension",
    "description": "Teamlock web extension",
    "version": "0.0.1",
    "background": {
        "service_worker": "/background.js"
    },
    "action": {
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "/content.js"
            ]
        }
    ],
    "permissions": [
        "tabs"
    ]
}

the way I forwarded the requests to background script :

runtime.sendMessage({method:"GET",endpoint:`/api/v1/workspace`,params:{}})
.then(res =>{
   console.log(res);
});

The listener on background script :

import {runtime} from "webextension-polyfill";
runtime.onMessage.addListener((request,sender) =>{
    console.log("bien reçu");
    return http.get(`/api/v1/workspace`)
})

Do you have any ideas ? I found also this issue on github : https://github.com/axios/axios/issues/2968

input field doesnt allow to edit

Hi guys I am trying to edit the input field below and cant.
I getting some data from a server and I am putting this data on the value of the input. The idea is that one we click the icon to allow the field to be editable but still cant edit.

This is the input with props customised:


 <input
          {...field}
          //   required={props.required}
          disabled={props.disabled}
          value={props.value}
          type={props.type}
          autoComplete={props.autoComplete}
          pattern={props.pattern}
          className={`mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm  rounded-md ${
            error ? 'border-red-500' : 'border-gray-500'
          }
          ${
            props.disabled
              ? 'disabled:shadow-none disabled:bg-slate-50 disabled:text-slate-500 disabled:border-slate-200'
              : 'border-gray-500'
          } `}
        />

And here is where I am actually using it. So once I click the icon its value comes true but cant edit inside the already value that returns from the server.


const [agent, setAgent] = useState<EstateAgentResponse | null>(null)
  const [enableField, setEnableField] = useState<boolean>(false)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const { id } = params

        const agentUsers = await getEstaAgentUsers(parseInt(id!, 10))
        const agent = await getEstateAgentById(parseInt(id!, 10))

        setAgentUsers(agentUsers)
        setAgent(agent)
      } catch (error) {
        // ToDo:
        // We should handle the error message
        toast.error(`${error}`)
      }
    }
    fetchData()
  }, [])

 const handleInputField = () => {
    setEnableField(!enableField)
  }

<PencilAltIcon className="block h-4 w-4" aria-hidden="true" onClick={handleInputField} />
                              <InputField
                                name="businessName"
                                label="Business name"
                                disabled={!enableField}
                                value={agent?.businessName}
                                type="text"
                                rules={{
                                  required: 'This is required',
                                }}
                              />