I’m unable to take value from text field and store it in a variable

I’m working on a web based chat app using HTML CSS and Javascript. I’m using an API called AivaChat API by aivinya. I want to take input from the text field id = “prompt” and store it in a variable called input which I can pass onto the API. Everything seems to be working correctly and I can see no errors on DevTools. This is my first time working with APIs, but it seems that the API is responding correctly as you can see it responds to the placeholder text.

This is what the output looks like:

This is my HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 id="titlish">Enter prompt: </h1>
    <input type="text" id="prompt" placeholder="Enter text">
    <button id="promptin" onclick="takePrompt()">Take Text</button>
    <button id="myButton" onclick="onClick()">Submit</button>
    <h2 id="gpt"></h2>

    <script src="./index.js"></script>
</body>
</html>

This is my Javascript code:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var input = "What is a placeholder?"

function takePrompt(){
    var input2 = document.getElementById("prompt").value;
    console.log(input2);
    input = input2;
}

var raw = JSON.stringify({
    "text": input
  }
);

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

function onClick(){

    let textEl = document.getElementById("gpt");

    fetch("https://api.aivinya.education/api/public/aivachat", requestOptions)
    .then(response => response.text())
    .then(result => {textEl.innerText = result;})
    .catch(error => console.log('error', error));
    console.log("working function")
}

I tried returning ‘input’ from the function and passing that onto the raw variable( ‘text’ field ) like so:

var input = function takePrompt(){
    var input2 = document.getElementById("prompt").value;
    console.log(input2);
    return input2;
}

var raw = JSON.stringify({
    "text": input
  }
);

And a few other things but the results don’t seem to change. I expected it to respond to the prompt in the text field [In this case to question “What is a problem” not “What is a place holder”]

Is there any way to use a variable in javascript document.querySelector(my var here) or document.getElementById(my var here)?

I have a html document with 113 buttons and I am using an EventListener on these buttons to accomplish 2 things:
1: Copy text from hidden textareas.
2: Apply CSS to span elements.

I currently have a an EventListener that gets the job done, but I have to code the EventListener for each individual element.

My goal is to accomplish this using 1 EventListener instead of 113.
If I can’t use a variable is there another way to accomplish this?

Please see code pens.
Version 1: Working, shortened to 5 code blocks for demo. https://codepen.io/learn4earn/pen/QWVBpqR

// Copy text from hidden textareas
const copyText001 = document.querySelector("#taCode001");
const codeButton001 = document.querySelector("#button001");
const toolTip001 = document.querySelector(".tooltip001");
codeButton001.addEventListener('click', function(){
taCode001.select();
toolTip001.classList.add("show");
setTimeout(function(){
    toolTip001.classList.remove("show");
},2000);

if(document.execCommand("copy")){
    copyText001.focus();
}else{
    alert("Something went wrong!");
}
});

Version 2: Not working with my attempt to use variables. https://codepen.io/learn4earn/pen/KKxBWoP

const buttons = document.getElementsByTagName("button");
            
            const buttonPressed = e => {
                var btnIdNumber = e.target.id;          // Get ID of Clicked Element
                console.log(btnIdNumber);              //  Dispaly ID of Clicked Element in Console
                btnIdNumber = btnIdNumber.slice(-3);  //   Trim the ID Down To Last 3 Characters
                console.log(btnIdNumber);            //    Dispaly Trimed ID Number in Console
                
                let taString = "#taCode";
                let taSplitString = Array.from(taString);
                taSplitString.push(btnIdNumber);            // Append Trimed ID Number of Clicked Element to string array
                let taJoinString = taSplitString.join("");
                let taCode = taJoinString;
                console.log(taCode);                        // Dispaly string in console
                //return taCode;
            
                let copyTextArea = document.querySelector(taCode); // Trying to use variable "taCode" as element selector 
                console.log(copyTextArea);
                taCode.select();
                if(document.execCommand("copy")) {              // Copy Content of Hidden textarea
                    copyTextArea.focus();
                } else {
                    alert("Something went wrong!");
                }
                  
                let toolTipString = ".tooltip";
                let toolSplitStr = Array.from(toolTipString);
                toolSplitStr.push(btnIdNumber);                 // Append Trimed ID Number of Clicked Element to string array
                let joinToolTip = toolSplitStr.join("");
                let tooltip = joinToolTip;
                console.log(tooltip);                           // Dispaly string in console                         
                //return tooltip;
                
                tooltip.classList.add("show");                  // Trying to use variable "tooltip" as element selector 
                setTimeout(function(){      
                    tooltip.classList.remove("show");
                },2000);
            }
                 
            for (let button of buttons) {
                button.addEventListener("click", buttonPressed);
            }

p.s. And yes, I know that .execCommand has been depricated, but I am not yet familliar with Clipboard API and async functions.

Uploading Large file over httpPost throws unknown error in Angular 14

I have a simple ractive angular form for uploading files, and there’s ASP.core for backend.
sending the file to the api over HTTP post stops midway after like 10 seconds and returns an UNKNOWN ERROR with code 0 only if the file is larger than around 10MB or so. small sized files are uploaded just fine.

The ASP.NET API as of now just returns a message after recieving the form and no proccessing. So the file won’t even reach the server. Plus, sending the same large files with Postman works just fine. and there’s no limit on file size on the Backend so the problem has to be the client-side.

I even rewrote the code using this tutorial. result is the same even though it works with Postman but my angular app fails.

progress: number;
message: string;
@Output() public onUploadFinished = new EventEmitter();

constructor(private http: HttpClient) { }

uploadFile = (files: any) => {
 if (files.length === 0) {
   return;
 }
 let fileToUpload = <File>files[0];
  const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);

 this.http.post('https://localhost:44468/api/upload', formData, { reportProgress: true, 
  observe: 'events' })
    .subscribe({
     next: (event: any) => {
       if (event.type === HttpEventType.UploadProgress)
         this.progress = Math.round(100 * event.loaded / event.total);
      else if (event.type === HttpEventType.Response) {
         this.message = 'Upload success.';
         this.onUploadFinished.emit(event.body);
       }
     },
     error: (err: HttpErrorResponse) => console.log(err)
   });
}

Template:

<div class="row" style="margin-bottom:15px;">
 <div class="col-md-3">
  <input type="file" #file placeholder="Choose file" (change)="uploadFile(file.files)" style="display:none;">
  <button type="button" class="btn btn-success" (click)="file.click()">Upload File</button>
</div>
<div class="col-md-4">
  <span class="upload" *ngIf="progress > 0">
    {{progress}}%
  </span>
  <span class="upload" *ngIf="message">
    {{message}}
  </span>
 </div>
</div>

the Error:

unknown error

Hence I have no Idea why the error occurs and no way to rectify it.
Keep in mind that there’s no problem uploading smaller files. It can’t be CORS issue since it works with postman and AllowAnyOrigin() ... is set.
I’ll gladly appreciate any help.

I can’t use infinite slider with swiper.js

I want make 100 page but width should be like 3 page ı tried to change css and javascript but nothing happened. Can you help me?

Hi ı am trying to make a slider for 100 page but ı can’t ı use swiper.js
var swiper = new Swiper(".mySwiper", { slidesPerView: 3, centeredSlides: true, spaceBetween: 10, grabCursor: true, pagination: { el: ".swiper-pagination", clickable: true, }, });
if ı write for “slidesPerView” 3 then ı can only see 3 page but if ı write 10 ı can see 10 page but they are really small THİS İS 3 PAGE
THİS İS 10 PAGE
I want make 100 page but width should be like 3 page ı tried to change css but nothing happened. Can you help me?

Imports from package are not resolved

I am developing an npm package which has both default and named exports for every module.
They export the same thing basically. And when installing and trying to import things as named imports in example app everything works fine, but the same approach does not work for docusaurus documentation. The typechecker there fails complaining that package does not have any named exports. In both places the same node version is used(v18). When looking in node_modules/package functions exist and they are exported

Module import export best practices in typescript/Javascript

Seeing both approaches used widely wanted to check what is the recommended way to do export from a folder of related modules. Is it good idea to have an index file which does reexport
and use it as an entry for all the modules in the folder? Or is it better to export and import individually

// /mymodule/index.ts
export * from "./A";
export * from "./B";

or maybe with explicit exports

// /mymodule/index.ts
export {a, aa} from "./A";
export {b, bb} from "./B";

and then use it as import {a, b} from ./mymodule

in this case, A or B can be folders as well and this can be e very neat way to expose folders functionality with its subfolders.

or is it better just not to use index file and import/export individually i.e.

import { a } from ./mymodule/A
import { b } from ./mymodule/B

How to concatenate php variable with javascript [duplicate]

I am working with php and javascript, Right now i am using “static url” in javascript but i want to use “dynamic url” ($url) in javascript, So how can i concatenate php variable in php ? Here is my current code

$url=base_url()."create";
echo 
"<script type='text/javascript'>
    var url ='https://xxxxxxxxxxxxx';
    window.location = url;
</script>";

How to fix OAuth 2.0 authorization that will soon be deprecated?

Object { error: “idpiframe_initialization_failed”, details: “You have created a new client application that uses libraries for user authentication or authorization that will soon be deprecated. New clients must use the new libraries instead; existing clients must also migrate before these libraries are deprecated. See the Migration Guide for more information.” }

Code

require('dotenv').config()

const express = require('express');
const app = express();
const cookieParser = require('cookie-parser')

// Google Auth
const {OAuth2Client} = require('google-auth-library');
const CLIENT_ID = '674825315286-ttgml4tvkv7impl21b6cviggcp3j7eem.apps.googleusercontent.com'
const client = new OAuth2Client(CLIENT_ID);
const PORT = 8000;

// Middleware
app.set('view engine', 'ejs');
app.use(express.json());
app.use(cookieParser());
app.use(express.static('public'));

app.get('/', (req, res)=>{
    res.render('index')
})

app.get('/login', (req,res)=>{
    res.render('login');
})

app.post('/login', (req,res)=>{
    let token = req.body.token;

    async function verify() {
        const ticket = await client.verifyIdToken({
            idToken: token,
            audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
        });
        const payload = ticket.getPayload();
        const userid = payload['sub'];
      }
      verify()
      .then(()=>{
          res.cookie('session-token', token);
          res.send('success')
      })
      .catch(console.error);

})

app.get('/profile', checkAuthenticated, (req, res)=>{
    let user = req.user;
    res.render('profile', {user});
})

app.get('/protectedRoute', checkAuthenticated, (req,res)=>{
    res.send('This route is protected')
})

app.get('/logout', (req, res)=>{
    res.clearCookie('session-token');
    res.redirect('/login')

})


function checkAuthenticated(req, res, next){

    let token = req.cookies['session-token'];

    let user = {};
    async function verify() {
        const ticket = await client.verifyIdToken({
            idToken: token,
            audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
        });
        const payload = ticket.getPayload();
        user.name = payload.name;
        user.email = payload.email;
        user.picture = payload.picture;
      }
      verify()
      .then(()=>{
          req.user = user;
          next();
      })
      .catch(err=>{
          res.redirect('/login')
      })

}


app.listen(PORT, ()=>{
    console.log(`Server running on port ${PORT}`);
})

i want to make google authentication with login and logout feature but an error like the one above, what i want to get is that login and logout feature

Thank You

Bottom Tab Navigator: ‘tabBarOptions’ is deprecated. Migrate the options to ‘screenOptions’ instead

I have a react native app.

and I have some navigation functionality. And everything works fine. But Every time the app starts. I get this warning:

Bottom Tab Navigator: 'tabBarOptions' is deprecated. Migrate the options to 'screenOptions' instead.

And this is my component:

const Tab = createBottomTabNavigator();

const TAB_ICON = {
    Dieren: "md-paw",
    Favorieten: "md-heart",
    Settings: "md-settings",
};

const Settings = () => (
    <SafeArea>
        <Text>Settings</Text>
    </SafeArea>
);

const createScreenOptions = ({ route }) => {
    const iconName = TAB_ICON[route.name];
    return {
        tabBarIcon: ({ size, color }) => <Ionicons name={iconName} size={size} color={color} />,
    };
};

export const AppNavigator = () => (
    <NavigationContainer>
        <Tab.Navigator
            screenOptions={createScreenOptions}
            tabBarOptions={{
                tabBarActiveTintColor: "tomato",
                tabBarInactiveTintColor: "green",
                tabBarStyle: [
                    {
                        display: "flex",
                    },
                    null,
                ],
            }}>
            <Tab.Screen name="Dieren" component={CategoryNavigator} />
            {/* <Tab.Screen name="Favorieten" component={CategoryNavigator} />
             */}
            <Tab.Screen name="Settings" component={Settings} />
        </Tab.Navigator>
    </NavigationContainer>
);


Question: How to suppress this warning?

Unable to pause/freeze Chrome Debugger when using input type=’date’?

i want to pause and inspect over the hovering date picker but I’m not able to pause the debugger and inspect over it.

this is the component code.

import React from "react";
import styled from "styled-components";

interface DatePickerProps {
    value?: Date;
    onChange?: (value: Date) => void;
    disabled?: boolean;
    className?: string;
  }
  

  
export const DatePicker = (props: DatePickerProps) => {
    const { onChange, disabled, className, value } = props
    const [selectedDate, setSelectedDate] = React.useState<Date | undefined>(value);

    const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const newDate = new Date(event.target.value);
        setSelectedDate(newDate);
        onChange && onChange(newDate);
    };
  
    return (
        <DatePickerWrapper className={className} disabled={disabled}>
            <DatePickerIcon className="far fa-calendar-alt" />
            <Input
                type="date"
                value={selectedDate?.toISOString().slice(0, 10)}
                onChange={handleDateChange}
                disabled={disabled}
                min={new Date().toISOString().slice(0, 10)}
  
            />
        </DatePickerWrapper>
    );
};
  
const DatePickerWrapper = styled.div<DatePickerProps>`
    display: flex;
    align-items: center;
    border: 1px solid gray;
    padding: 8px;
    border-radius: 4px;
    cursor: ${(props) => (props.disabled ? 'not-allowed' : 'pointer')};
    opacity: ${(props) => (props.disabled ? 0.5 : 1)};
    transition: all 0.2s ease-in-out;
    background-color: #1c1c1c;
  
    &:hover {
      border-color: #2196f3;
    }
  `;
  
const Input = styled.input`
    border: none;
    font-size: 16px;
    width: 100%;
    background-color: transparent;
    color: white;
  
    &::-webkit-calendar-picker-indicator {
      filter: invert(1);
    }
  
    &:focus {
      outline: none;
    }
  `;
  
const DatePickerIcon = styled.i`
    font-size: 16px;
    color: gray;
    margin-right: 8px;
    filter: invert(1);
  `;

can someone help me inspect over it.

normally, opening devtools -> sources -> f8 should work but over here it doesn’t.

for context, I’m able to f8 and freeze when this the datepicker isn’t open. it’s an issue only when it’s open 🙁

Freeze screen in chrome debugger / DevTools panel for popover inspection?

referring to this answer for freezing ^

Truncating longer text and appending “…” to it, is not working in jsx

I am building a react app I have a long text in .map response which I am trying to truncate using split and slice method and adding at the last to the long text. But It is not working after so many modified truncate functions.

function truncate(text) {
  const words = text.split(' ');
  const truncated = words.slice(0, 30).join(' ');

  if (words.length > 30) {
    return `${truncated}...`;
  }

  return truncated;
}


function Blogs(props) {


   return (
         <>
             {props.blogs.map((res) => <>
                <div>
                      {truncate(res.title)}
                <div/>
              </>}
         </>
    
    )
}

I have also tried by modifying the truncate function like.

function truncate(text) {
  const words = text.split(' ');
  const truncated = words.slice(0, 30).join(' ');
  if (words.length > 30) {
    return truncated + '...';
  }
  return truncated;
}

It is not working after all.

Any help would be much Appreicated. Thank You

Object oriented conception

I have a main class named Rule with a param attribute:

class Rule {
  param = {}
  constructor (param) {
    console.log(this.param)
  }
}

and several subclasses as exemple:

class SubRule extends Rule {
  param = {
    subparam1: 'test'
  }
  constructor (param) {
    super(param)
  }
}

let myrule = new SubRule()
>> Object {  } instead of Object { subparam1: 'test' }

When instantiate a new object, I would like to fuse this.param and the param parameter given to the constructor for all the subclasses. I wanted to add the logic in the Rule class, however, when accessing this.param in the Rule.constructor class I do not access the child this.param attribute but the one defined in Rule.
What would be the right design to properly initiate this.param in all subclasses ?

Issue with resetting inputs

I have a problem resetting the inputs from “AddressForm” component and only when they are containing data from “deviceAddress”, others are working fine when handleReset() is triggered.
Here are my components:

The parent component:


const styles = (theme: Theme) =>
    createStyles({
        root: {
            margin: 0,
            padding: 16,
        },
        closeButton: {
            position: 'absolute',
            color: '#6b718b',
            right: 16,
            top: 24,
        },
    });

export interface ModalFormResponseModel {
    success: boolean;
    content: string;
}

export interface DialogTitleProps extends WithStyles<typeof styles> {
    id: string;
    onClose: () => void;
}

const DialogTitle = withStyles(styles)((props: DialogTitleProps) => {
    const { classes, onClose, ...other } = props;
    return (
        <MuiDialogTitle disableTypography className={classes.root} {...other}>
            {onClose ? (
                <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
                    <span className="uk-icon" uk-icon="close" style={{ width: 18, color: '#212d40' }}></span>
                </IconButton>
            ) : null}
        </MuiDialogTitle>
    );
});

const SaveButton = withStyles((theme: Theme) => ({
    root: {
        color: 'white',
        backgroundColor: '#212d40',
        borderRadius: 0,
        margin: 16,
        textTransform: 'none',
        fontFamily: 'Inter',
        fontSize: 16,
        fontWeight: 500,
        padding: '10px 32px',
        '&:hover': {
            backgroundColor: '#212d40',
        },
    },
}))(Button);

const ResetButton = withStyles((theme: Theme) => ({
    root: {
        color: '#6b718b',
        backgroundColor: 'transparent',
        borderRadius: 0,
        margin: 16,
        textTransform: 'none',
        fontFamily: 'Inter',
        fontSize: 16,
        fontWeight: 500,
        padding: '10px 16px',
        boxShadow: 'none',
        '&:hover': {
            backgroundColor: 'transparent',
            boxShadow: 'none',
        },
    },
}))(Button);

const DialogActions = withStyles((theme: Theme) => ({
    root: {
        margin: 0,
        padding: theme.spacing(1),
        backgroundColor: '#f8f8fa',
    },
}))(MuiDialogActions);

function WidgetCustomerData(props): JSX.Element {
    const { customer, open, deviceAddress } = props;
    const [customerData, setCustomerData] = useState(customer);
    const [deviceLocationAddress, setdeviceLocationAddress] = useState(deviceAddress)
    const { t } = useTranslation();

    const handleClose = () => {
        props.handleClose?.();
    };

    const handleSubmit = async (e) => {
        e && e.preventDefault();
        const formUrl = 'https://fetch.mock/m-widget-customer-data/addCustomerData';
        const formData = new FormData(e.target);

        const response = await fetch(formUrl.toString(), {
            method: 'POST',
            body: formData,
            credentials: 'same-origin',
        });

        const data = await response.json();
    };

    const handleReset = () => {
        setCustomerData(customer);
        setdeviceLocationAddress(deviceAddress);
    };

    const handleChange = (e) => {
        const fieldName = e.target.name.split(".");
        const value = e.target.value;
        console.log('fieldname', fieldName)
        if (fieldName.length === 2) {
          setCustomerData((prevState) => ({
            ...prevState,
            [fieldName[0]]: {
              ...prevState[fieldName[0]],
              [fieldName[1]]: value,
            },
          }));
        } else if (fieldName[0] === 'address' && deviceAddress && deviceAddress.hasOwnProperty(fieldName[1])) {
            setCustomerData((prevState) => ({
              ...prevState,
              address: {
                ...prevState.address,
                [fieldName[1]]: deviceAddress[fieldName[1]],
              },
            }));
          } else {
          setCustomerData((prevState) => ({
            ...prevState,
            [fieldName[0]]: value,
          }));
        }
      };

    return (
        <div className="m-widget-customer-data">
            <Dialog
                onClose={handleClose}
                open={open}
                aria-labelledby="customized-dialog-title"
                PaperProps={{
                    style: { borderRadius: 20, minWidth: '80%', maxHeight: 'fit-content' },
                }}>
                <DialogTitle id="customized-dialog-title" onClose={handleClose} />
                <Typography style={{ marginTop: 20, paddingLeft: 48, fontSize: 32, fontWeight: 600 }}>{t('Edit Customer Data')}</Typography>
                <form onSubmit={handleSubmit}>
                    <div style={{ paddingLeft: 48, paddingRight: 48 }} onChange={handleChange}>
                        <CustomerData customer={customerData} deviceAddress={deviceLocationAddress} />
                    </div>
                    <DialogActions>
                        <ResetButton onClick={handleReset} variant="contained" color="primary">
                            {t('Reset')}
                        </ResetButton>
                        <SaveButton type="submit" variant="contained" color="primary">
                            {t('Save')}
                        </SaveButton>
                    </DialogActions>
                </form>
            </Dialog>
        </div>
    );
}
export default WidgetCustomerData;

CustomerData component:

export default ({nextStepAction, customer, handleChange, deviceAddress }: MoleculeSystemManagementCustomerDataProps): JSX.Element => {
  const [addressIsDifferent, setAddressIsDifferent] = useState(true);
  const { t } = useTranslation();
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if(nextStepAction) nextStepAction(new FormData(e.target as HTMLFormElement));
  }

  return (
    <div className='m-customer-data'>
      <CustomerForm customer={customer} handleChange={handleChange} />
      <AddressForm formId='customer' formGroupHeader='Residence' customer={customer} handleChange={handleChange} />
      
      <Checkbox label={t("Device address is different than customer address")} id="addressIsDifferent" checked={addressIsDifferent} onChange={(e) => {
        setAddressIsDifferent(e.target.checked)
      }} />

      {addressIsDifferent && <AddressForm formId='device' formGroupHeader='Customer Data System Location' customer={customer} deviceAddress={deviceAddress} handleChange={handleChange} />}
    </div>
  );
}

AddressForm component:

import React from 'react';
import { useTranslation } from 'react-i18next';
import { Grid } from '@material-ui/core';
import InputField from '/components/atoms/a-input/react/components/a-input.component';
import { DeviceOwner } from '/global/js/modules/SystemManagement/types/DeviceOwner';
import { useStyles } from '../hooks/useStyles';
import { LocationAddress } from '/global/js/modules/SystemManagement/types/LocationAddress';
export interface AddressFormProps {
    formId: string;
    formGroupHeader: string;
    customer: DeviceOwner;
    deviceAddress?: LocationAddress;
    handleChange?: () => void;
}

function AddressForm({ formId, formGroupHeader, customer, deviceAddress, handleChange }: AddressFormProps): JSX.Element {
    const classes = useStyles();
    const { t } = useTranslation();
    const {
        address: { street, house_number, city, zip_code },
    } = customer ?? {};
    const { street: device_street, house_number: device_house_number, city: device_city, zip_code: device_zip_code } = deviceAddress ?? {};
    console.log('street', street);
    console.log('deviceAddress addressForm', deviceAddress);
    return (
        <Grid container className={classes.borderedRow}>
            <Grid item xs={12} md={12} className={classes.rowTitle}>
                <span>{t(formGroupHeader)}</span>
            </Grid>
            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <div>
                    <InputField
                        type="label"
                        id="address"
                        name={formId === 'customer' ? 'address.street' : 'deviceAddress.street'}
                        value={formId === 'customer' ? street : device_street}
                        onChange={handleChange}
                        label={t('Street').toString()}
                    />
                </div>
            </Grid>

            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <InputField
                    type="label"
                    id="addressNr"
                    name={formId === 'customer' ? 'address.house_number' : 'deviceAddress.house_number'}
                    value={formId === 'customer' ? house_number : device_house_number}
                    onChange={handleChange}
                    label={t('Number').toString()}
                />
            </Grid>

            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <InputField 
                    type="label" 
                    id="zip" 
                    name={formId === 'customer' ? 'address.zip_code' : 'deviceAddress.zip_code'}
                    value={formId === 'customer' ? zip_code : device_zip_code} 
                    onChange={handleChange} 
                    label={t('ZIP').toString()} 
                />
            </Grid>

            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <InputField 
                    type="label" 
                    id="city" 
                    name={formId === 'customer' ? 'address.city' : 'deviceAddress.city'}
                    value={formId === 'customer' ? city : device_city} 
                    onChange={handleChange} 
                    label={t('ORT').toString()} 
                />
            </Grid>
        </Grid>
    );
}
export default AddressForm;

CustomerForm component:

import React from 'react';
import { useTranslation } from 'react-i18next';
import { Grid } from '@material-ui/core';
import InputField from '/components/atoms/a-input/react/components/a-input.component';
import { DeviceOwner } from '/global/js/modules/SystemManagement/types/DeviceOwner';
import { useStyles } from '../hooks/useStyles';

export interface CustomerForm {
customer: DeviceOwner;
handleChange?: () => void;
}

function CustomerForm({ customer, handleChange }: CustomerForm): JSX.Element {
    const classes = useStyles();
    const { t, i18n } = useTranslation();
    const { owner_firstname, owner_lastname, owner_phone, owner_email } = customer ?? {};
    console.log('owner first name', owner_firstname);
    return (
        <Grid container className={classes.borderedRow}>
            <Grid item xs={12} md={12} className={classes.rowTitle}>
                <span>{t('Customer Data')}</span>
            </Grid>
            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <div>
                    <InputField
                        type="label"
                        id="firstName"
                        name="owner_firstname"
                        value={customer && owner_firstname}
                        onChange={handleChange}
                        label={t('First Name').toString()}
                    />
                </div>
            </Grid>

            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <InputField
                    type="label"
                    id="lastName"
                    name="owner_lastname"
                    value={customer && owner_lastname}
                    onChange={handleChange}
                    label={t('Last Name').toString()}
                />
            </Grid>

            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <InputField
                    type="label"
                    id="phone"
                    name="owner_phone"
                    value={customer && owner_phone}
                    onChange={handleChange}
                    label={t('Phone').toString()}
                />
            </Grid>

            <Grid item xs={12} sm={6} md={3} className={classes.formColumn}>
                <InputField
                    type="label"
                    id="email"
                    name="owner_email"
                    value={customer && owner_email}
                    onChange={handleChange}
                    label={t('Email').toString()}
                />
            </Grid>
        </Grid>
    );
}
export default CustomerForm;

I’ve tried different approaches in handleChange(), the data from deviceAddress is updated, but when I try to reset the data, the inputs are not reset, only those that are containing data from deviceAddress, others are working fine. I don’t catch the issue here, someone cand help me solve this?

Multiple Api Calls with Promise.all does return undefined

I have an array of marinas, for which I want to make api calls. The Problem is that the result will arrive after, the return. Can anyone help me please?

 getAllChangeRequests(): Observable<any> {
        console.log('getAllChangeRequests');

        this.changeRequestArray = []
        this.state.setUpdating(true);

        return this.userOrganisationFavouritesFacade.loadAll().pipe(map(async marinas => {
            const promises: U2bChangeRequest[][] = []

            const test = await Promise.all(marinas.map(marina => {
                if (marina.organisation?.bcm_tenant_id) {
                    console.log('hallo2');

                    this.getMany((new HttpParams().set('tenantId', `${marina.organisation?.bcm_tenant_id}`))).subscribe(changeRequests => {
                        console.log(changeRequests);

                        promises.push(changeRequests)
                    })

                }
            }))

            console.log(test);
            
           


            this.state.setChangeRequests(this.changeRequestArray);
            this.state.setUpdating(false);

            return promises;


        }));


    }

Calling member function from event listener callback function in JavaScript class [duplicate]

I need to call a member function from the callback function in an event listener which is also in another member function. Here is a simplified example:

class C {

  finished() {
    console.log ('over');
  }
  
  timer() {
    console.log('started')
    setTimeout(function fct() {
        this.finished();
    },500);
  }
}


let c = new C();

c.timer();

I get the following result : Uncaught TypeError: this.finished is not a function". I understand that the callback function is no longer member of the class C.

Is there a way to call the finished() member function from the callback function?

Here is a JSFiddle