How to wrap if condition in then function in javascript?

i am new to learning javascript. i am currently trying to wrap if condition inside a then function.

below is my code,

const createType = ({
    firstTypes = [],
    secondTypes = [],
    ...allType
    } = {}, skip = true) => {
    const builtType = buildType(allType);
    let finalType;
    let finalSecondTypes;

    return apiPostType(builtType)
    .then(waitForSync(cy.apiGetTypeWithRetry))
    .then(createdType => {
    finalType = keysToCamelCase(createdType);
    const firstTypesToCreate = firstTypes.map(
        firstType => () =>
        cy.createFirstType({
            ...firstType,
            allType: createdType.id,
        })
    );

the above code works fine. now i want to execute waitForSync(apiGetTypeWithRetry) only if skip is set to false. hence i tried like below,

const createType = ({
    firstTypes = [],
    secondTypes = [],
    ...allType
    } = {}, skip = true) => {
    const builtType = buildType(allType);
    let finalType;
    let finalSecondTypes;

    return apiPostType(builtType)
    .then(createdType => {
        if(skip = false) {
            waitForSync(cy.apiGetTypeWithRetry);
        }
    })
    .then(createdType => { //here createdType is undefined
    finalType = keysToCamelCase(createdType);
    const firstTypesToCreate = firstTypes.map(
        firstType => () =>
        cy.createFirstType({
            ...firstType,
            allType: createdType.id,
        })
    );

but after adding if condition in the .then() function the createdType for the next .then() function is undefined. i am not sure how to pass the promise from the previous .then function.

could someone help me with this. thanks.

How can I get the website URL using Voiceflow Chatbot?

I’m trying to add a feature to my Voiceflow chatbot where I can save as a variable the website URL. I need it for the chatbot flow so it should be saved as a variable inside the flow.

I tried using the javascript module:

websiteURL = window.location.href

It says that window is not defined.

I also asked to the AI Voiceflow Assistant an it told me to modify the launching code to get the url as a variable, it didn’t work neither.

<script type="text/javascript">
  (function(d, t) {
      var v = d.createElement(t), s = d.getElementsByTagName(t)[0];
      v.onload = function() {
        window.voiceflow.chat.load({
          verify: { projectID: 'XXXXCURRENT_IDXXXX' },
          url: 'https://general-runtime.voiceflow.com',
          versionID: 'production',
          variables: {
            websiteURL: window.location.href
          }
        }).then(() => {
          setTimeout(function() {
                  window.voiceflow.chat.open();
                }, 200);
        });
      }
      v.src = "https://cdn.voiceflow.com/widget/bundle.mjs"; v.type = "text/javascript"; s.parentNode.insertBefore(v, s);
  })(document, 'script');
  </script>```


behaviour of setTimeout() in keeping track of variables? [closed]

I was coding recently and was stuck scratching my head over why, even when I pass the string that is initialised already, as a parameter, the setTimeout’s callback function still prints it as undefined.
Does it not keep track of the variable it needs later?

This is the simple illustration:

console.log("lets start");
const str="123";
setTimeout((str)=>console.log(str),5000);

so should i never pass an argument in setTimeout?

First class functions with callback

I am learning about functional programming, and have a question at this example in the book Mostly Adequate Guide:

// this line
ajaxCall(json => callback(json));

// is the same as this line
ajaxCall(callback);

From what I see, ajaxCall takes json as argument. But, callback is not a JSON. Part of the confusion is that I do not know what ajaxCall is – is it a generic placeholder here, or a established function in the wild?

How are the above two lines equivalent?

Match a Regex Pattern that doesn’t follow the serial arrangement in the pattern

How do i match a string to a regex pattern in javascript, but the string does not have to follow the serial arrangement in the regex Pattern.
The regex pattern test against a string containing brackets with the conditions that;

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.
  • Every close bracket has a corresponding open bracket of the same type.

This is what i tried;

const pattern = /^(())*({})*([])*$/

if i test it against these strings, it works fine

console.log(pattern.test("(){}[]")) //returns true
console.log(pattern.test("(]") //returns false

but if change the order the brackets appear in the regex then i get false

console.log(pattern.test("{}()[]") // returns false

I want the string of brackets to match the pattern no matter which brackets comes first or second as long as they meet the above conditions

Getting the error ” Should have a queue” when using React-Query mutation

I’m trying to figured out how to implement react-query in my react-native app. I’m executing a simple firebase login function from react-query mutation. Then in my signIn component I will call the mutation from a submit button. When I thought it was this simple, I’m keep getting “Error: Should have a queue. This is likely a bug in React. Please file an issue.” However, the code was able to reach the success part of the mutation. Any helps on this would be appreciated as there are only few guidances online that showcase the implementation of react-query with firebase.

These are the full errors:

Running "App" with {"rootTag":231,"initialProps":{}}
 ERROR  Warning: React has detected a change in the order of Hooks called by SignIn. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useRef                     useRef
2. useState                   useRef
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    in SignIn (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by SignMain)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in KeyboardAvoidingView (created by SignMain)
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by SignMain)
    in SignMain (created by AuthNavigation)
    in AuthNavigation (created by App)
    in EnsureSingleNavigator
    in BaseNavigationContainer
    in ThemeProvider
    in NavigationContainerInner (created by App)
    in WithSplashScreen (created by App)
    in App (created by AppWrapper)
    in QueryClientProvider (created by AppWrapper)
    in AppWrapper
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in App(RootComponent)
 ERROR  Error: Should have a queue. This is likely a bug in React. Please file an issue.

This error is located at:
    in SignIn (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by SignMain)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in KeyboardAvoidingView (created by SignMain)
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by SignMain)
    in SignMain (created by AuthNavigation)
    in AuthNavigation (created by App)
    in EnsureSingleNavigator
    in BaseNavigationContainer
    in ThemeProvider
    in NavigationContainerInner (created by App)
    in WithSplashScreen (created by App)
    in App (created by AppWrapper)
    in QueryClientProvider (created by AppWrapper)
    in AppWrapper
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in App(RootComponent), js engine: hermes

signIn.tsx

function SignIn() {

  const signInMutation = authAPI_login;
  const validationSchema = loginValidation;

  type SignInFormSchema = z.infer<typeof validationSchema>;

  const {control, handleSubmit, setFocus} = useForm<SignInFormSchema>({
    defaultValues: loginFormData,
    resolver: zodResolver(validationSchema),
  });

  const onSubmit = async (data: any) => {
     signInMutation.mutate({
          email: data.email,
          password: data.password,
        });
  };

  return (
    <View style={styles.rootContainer}>
      <View style={styles.inputContainer}>
        <TxtInput
          height={40}
          width={300}
          control={control}
          name="email"
          placeholder="Email"
          inputMode="email"
          nextFocus={true}
          isLoading={false}
          secureTextEntry={false}
          setNextFocus={() => {
            setFocus('password');
          }}
        />
      </View>
      <View style={styles.inputContainer}>
        <TxtInput
          height={40}
          width={300}
          control={control}
          name="password"
          placeholder="Password"
          inputMode="text"
          isLoading={false}
          secureTextEntry={true}
        />
      </View>
        <Button
          height={40}
          width={300}
          outline={true}
          isListening={true}
          isLoading={false}
          // onPress={handleSubmit(onSubmit)}
          onPress={() => {return onSubmit('test') }}
          >
          Sign In
        </Button>
     
    </View>
  );
}

api.tsx

export async function authSV_login(email: string, password: string) {
  return auth()
    .signInWithEmailAndPassword(email, password)
    .then((auth) => {
      return true
    })
    .catch(error => {
      if (error.code === 'auth/email-already-in-use') {
        console.log('That email address is already in use!');
      }

      if (error.code === 'auth/invalid-email') {
        console.log('That email address is invalid!');
      }

      return false
    });
}

export const authAPI_login = useMutation({
    mutationFn: ({ email, password }: {email: string, password: string}) => authSV_login(email, password),
    onSuccess: async (data) => {
      console.log('success', data);
    },
    onError: async (error) => {
      console.log('error', error);
    },
})

Permission Error When Executing Vertex AI Fine Tuning Job with Node.js: Service Account Roles Insufficient?

I’m using a pipeline job to fine tune a text-bison model with Vertex AI on GCP. My API is logged using a dedicated service account. It has the roles : Vertex AI Service Agent and Service Accounts User.

I’m using this Node.js code :

import aiplatform from '@google-cloud/aiplatform';

class ModelTuningController {
  initiateModelTuning = catchAsync(async (req, res) => {
    const { modelDisplayName = 'fineTunedTest' } = req.body;

    const { PipelineServiceClient } = aiplatform.v1;

    const location = 'us-central1';
    const project = 'projectID';
    const model = 'text-bison@001';

const pipelineClient = new PipelineServiceClient({
  apiEndpoint: `${location}-aiplatform.googleapis.com`,
  keyFilename: config.vector_store_key_filename,
});

const parameters = {
  source_model: { stringValue: model },
  train_dataset: {
    stringValue: 'gs://path/file.jsonl',
  },
  tuned_model_display_name: {
    stringValue: modelDisplayName,
  },
  epochs: {
    numberValue: 4,
  },
  learning_rate_multiplier: {
    numberValue: 1,
  },
};

const runtimeConfig = {
  gcsOutputDirectory: 'gs://output-path',
  parameterValues: parameters,
};

try {
  const parent = `projects/${project}/locations/${location}`;
  const pipelineJob = {
    displayName: modelDisplayName,
    runtimeConfig,
  };

  const request = {
    parent,
    pipelineJob,
  };

  const [response] = await pipelineClient.createPipelineJob(request);

  return sendResponse(res, {
    message: ModelTuningMessages.jobInitiated(response.name),
  });
} catch (err) {
  return sendError(
    err,
    new ApiError(
      httpStatus.INTERNAL_SERVER_ERROR,
      ModelTuningMessages.jobError


       )
      );
    }
  });
}

export default ModelTuningController;

I have the following error : You do not have permission to act as service_account: ${projectID}[email protected]. (or it may not exist).

The problem is ${projectID}[email protected] is the project default service account. My guess it that my service account should act as the default service account of the project.

Does my service account is missing a role to execute the fine tuning job on Vertex AI ?

Issue with total score function ( angular)

I have a feature with three sections . The first section is used to caculate BMI and then that BMI is used to give a score to that section this then should be added to the total score . The issue is that whatever the BMI is the total score is always shown as 0 that is not correct.

Here is the relevant code . Any help working out what i have done wrong would be very helpful.

 updateBMI(sectionIndex: number, choices: any[]): void {
    // Find the choices for height and weight
    const heightChoice = choices.find(choice => choice.label === "Height(cm)");
    const weightChoice = choices.find(choice => choice.label === "Weight (kg)");
  
    // Check if both height and weight choices are found
    if (heightChoice && weightChoice) {
      const height = heightChoice.value;
      const weight = weightChoice.value;
  
      // Perform BMI calculation
      const bmi = this.calculateBMI(height, weight);
  
      // Calculate section score
      const sectionScore = this.calculateSection1Score(sectionIndex, bmi);
  
      // Update BMI Score choice in choices array
      const bmiScoreChoice = choices.find(choice => choice.label === "BMI Score");
      if (bmiScoreChoice) {
        bmiScoreChoice.value = Math.round(bmi).toString();
      }
  
      // Update the original Sections array with the modified choices
      this.Sections[sectionIndex].choices = choices;
  
      // Update the section score property
      this.sectionScore = sectionScore;
  
      // Calculate total score
      this.calculateTotalScore();
    }
  }
  calculateBMI(height: number, weight: number): number {
    // BMI formula: weight (kg) / height (m) ^ 2
    const bmi = weight / Math.pow(height / 100, 2); // Convert height from cm to meters
    return Math.floor(bmi);
  }calculateSection1Score(sectionIndex: number, bmi: number): number {
    let sectionScore: number;
    if (bmi > 20) {
      sectionScore = 0; // Obese
    } else if (bmi >= 18.5 && bmi <= 20) {
      sectionScore = 1;
    } else {
      sectionScore = 2;
    }
    // Recalculate total score whenever the section score changes
    this.calculateTotalScore();
  
    return sectionScore; 

// Return the calculated section score
  }
 calculateTotalScore(): void {
    let totalScore = 0;

    // Calculate total score from sectionScore
    if (this.sectionScore !== null) {
      totalScore += this.sectionScore;
    }

    // Calculate total score from score property in section 2
    if (this.score !== null) {
      totalScore += this.score;
    }

    // Calculate total score from selectedOptions in section 3
    for (const key of Object.keys(this.selectedOptions)) {
      console.log(this.selectedOptions[key]);
      totalScore += this.selectedOptions[key].score;
    }

    // Assign the calculated total score to the totalScore property
    this.totalScore = totalScore;
  }

I have tried updating the updateBMI function but not fixed it.

Problems changing div to other div

i want to perform these tasks on datatable Initialization

How can i remove class to all td
i have tried to do this

$('td', row).removeClass('dtr-control');

but not working

also i tried to change the div of this dtable_wrapper

enter image description here
to this

<div class="tb10 info"> 

but not working

<script type="text/javascript">
    $(document).ready(function() {
        $("#detail").dataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "scpp.php",
                "type": "POST",
                "dataType": "json"
            },

            rowCallback: function (row, data) {
            $('td', row).removeClass('dtr-control'); 
            $('td:eq(2)', row).html('<a href="order.php?d=' + data[2] + '" role="button" class="btn"> <span class="spinn" role="status"></span>>' + data[2] + '</a>'');
        }
        $('#dtable_wrapper').replaceWith('<div class="tb10 info">');
    
        });
    }); 
</script>

After using Draw method pagination not working properly in Datatable 5

I am using draw() method for dynamic adding data in data table.

After draw we are adding more data in datatable then paging count should be update but page number same it’s not updated in datatable.

Below code we are using for load datatable.

$('#example').DataTable({ lengthChange: false, destroy: true, autoWidth: false, columns: [{ data: 'id', name: 'id' }, { data: 'test1', name: 'test1' }, { data: 'test2', name: 'test2' }], order: [[0, 'asc']], paging: true, pagingType: "full_numbers", pageLength: 10, searching: true, ordering: true, info: true, bAutoWidth:false, bPaginate: true, columnDefs: [{ "targets": 'no-sort', "orderable": false, }], //dom: '<<"pagination-top"lB><t><"pagination-wrap"<"pagination-left"i>p>', language: { "paginate": { "previous": pagination.previous, "next": pagination.next }, } }) .rows .add(dataJson) .order([0, 'asc']) .search('') .draw();

As per image here total 12 records are there and I set per page 10 records.

As per that here 2 page display in pagination but it’s display only 1 page.

enter image description here

When I click on next button then it’s working fine but on page load it’s not working.

Can anyone help me for this issue?

Number of all page should be display here after dynamic data updated in datatable.

Discord JS command with autocomplete dont Work

the autocomplete works fine but when im trying to execute the command it stops and idk why.. even the conditional i think the problem is in the autocomplete maybe i can be on a loop but idk how to handle that
my index is fine, it gives no error it just stops when i press enter to execute the command.

const { SlashCommandBuilder } = require('discord.js');
const { joinVoiceChannel, VoiceConnectionStatus } = require('@discordjs/voice');
const SpotifyWebApi = require('spotify-web-api-node');

const spotifyApi = new SpotifyWebApi({
    clientId: process.env.CLIENT_IDP,
    clientSecret: process.env.CLIENT_SECRET
});


module.exports = {
    data: new SlashCommandBuilder()
        .setName('play')
        .setDescription('Makes the bot say the provided text.')
        .addStringOption(option =>
            option.setName('cancion')
                .setDescription('The text you want the bot to say.')
                .setRequired(true)
                .setAutocomplete(true)),

                async autocomplete(interaction) {
                    try {
                        const focusedValue = interaction.options.getFocused();
                        
                        // Verificar si el valor enfocado está vacío o no definido
                        if (!focusedValue) {
                            return;
                        }
                        
                        const credenciales = await spotifyApi.clientCredentialsGrant();
                        spotifyApi.setAccessToken(credenciales.body.access_token);
                        let choices = [];
                
                        // Buscar canciones en Spotify basadas en el texto enfocado
                        const searchResults = await spotifyApi.searchTracks(focusedValue, { limit: 15 });
                        choices = searchResults.body.tracks.items.map(track => ({ name: track.name, value: track.uri }));
                
                        await interaction.respond(choices);
                    } catch (error) {
                        console.error("Error al realizar autocompletado de Spotify:", error);
                        // Manejar el error
                    }
                },

    async execute(interaction) {
        const voiceChannel = interaction.member.voice.channel;

        if (voiceChannel) {
            await interaction.reply("name song");
            try {
                // Unirse al canal de voz
                const connection = joinVoiceChannel({
                    channelId: voiceChannel.id,
                    guildId: interaction.guild.id,
                    adapterCreator: interaction.guild.voiceAdapterCreator
                });

            
                connection.on('stateChange', (_, newState) => {
                    if (newState.status === VoiceConnectionStatus.Disconnected) {
                        // Manejar la desconexión del canal de voz
                    }
                });

                // Desconectar después de 5 segundos
                setTimeout(() => {
                    connection.destroy();
                }, 5000);
            } catch (error) {
                console.error("Error al unirse al canal de voz:", error);
                await interaction.followUp({ content: "Hubo un error al unirse al canal de voz.", ephemeral: true });
            }

        } else {
            await interaction.reply({ content: "El usuario no está en un canal de voz.", ephemeral: true });
        }
    },
};

Recording Canvas With Logo Results in Segmented Audio

I was trying to implement the Screen Recording With Video and a logo using the RecordRTC library but found out that while using the example shown in

https://www.webrtc-experiment.com/RecordRTC/simple-demos/show-logo-on-recorded-video.html

results in segmented audio in the recording.

Here is a reproducible fiddle: https://jsfiddle.net/kiran589/L34bdhu7/5/

The code is like:

var videoPreview = document.getElementById('video-preview');
var logoImage = document.getElementById('logo-image');
var waitImage = document.getElementById('wait-image');

navigator.mediaDevices.getUserMedia({video: true, audio: true}).then(function(camera) {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    canvas.style = 'position: absolute; top: 0; left: 0; opacity: 0; margin-top: -9999999999; margin-left: -9999999999; top: -9999999999; left: -9999999999; z-index: -1;';
    document.body.appendChild(canvas);

    var video = document.createElement('video');
    video.autoplay = true;
    video.playsinline = true;
    video.srcObject = camera;

    var canvasStream = canvas.captureStream(15);

    var audioPlusCanvasStream = new MediaStream();

    // "getTracks" is RecordRTC's built-in function
    getTracks(canvasStream, 'video').forEach(function(videoTrack) {
        audioPlusCanvasStream.addTrack(videoTrack);
    });

    // "getTracks" is RecordRTC's built-in function
    getTracks(camera, 'audio').forEach(function(audioTrack) {
        audioPlusCanvasStream.addTrack(audioTrack);
    });

    var recorder = RecordRTC(audioPlusCanvasStream, {
        type: 'video'
    });

    recorder.setRecordingDuration(10 * 1000).onRecordingStopped(function() {
        var blob = recorder.getBlob();
        recorder = null;
        camera.stop();

        videoPreview.srcObject = null;
        videoPreview.src = URL.createObjectURL(blob);
    });

    recorder.startRecording();

    videoPreview.srcObject = canvasStream;

    var tries = 0;
    (function looper() {
        if(!recorder) return; // ignore/skip on stop-recording

        tries += 100;

        canvas.width = 320;
        canvas.height = 240;

        // show hello.png for one second
        if(tries < 5000 || tries > 6000) {
            context.drawImage(video, 0, 0, canvas.width, canvas.height);

            // context.drawImage(logoImage, parseInt(canvas.width / 2) - parseInt(logoImage.width / 2), canvas.height - logoImage.height - 10);
            // context.drawImage(logoImage, parseInt(canvas.width / 2) - parseInt(32 / 2), canvas.height - 32 - 10, 32, 32);
            context.drawImage(logoImage, 10, 10, 32, 32);
        }
        else {
            context.drawImage(waitImage, 0, 0, canvas.width, canvas.height);
        }

        // repeat (looper)
        setTimeout(looper, 100);
    })();
}).catch(function(error) {
    alert('Unable to capture camera. Please check console logs.');
    console.error(error);
});

If you go to the link and start recording, and say aaaaaaaaaaaaaaaaaaaa, then the recording outputs the audio like aaaa aaa aaa.

Is this a bug in RecordRTC?
Is there any way to get smooth audio and video in the recording while using canvas recording?

Thanks for your help in advance.

JSONBION.IO API for update

I created three pages of createUser.js, UpdateUser.js, and readUser.js and index.html which simply collects user details of employees and store them. I used the create file, it worked and created a JSON data. I used the readUser file and it worked to read uses. I even added more user details manually so I can read the JSON file, but the updateUser is overriding the JSON data inside my bin and adding the new user details.

I have read the documentation of jsonbin and I still can’t find what I am doing wrong.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Details Form</title>
    <style>
        /* Add your CSS styles here */
    </style>
</head>
<body>
    <h1>User Details Form</h1>
    <form id="userForm">
        <label for="firstName">First Name:</label>
        <input type="text" id="firstName" name="firstName" required><br>

        <label for="lastName">Last Name:</label>
        <input type="text" id="lastName" name="lastName" required><br>

        <label for="age">Age:</label>
        <input type="number" id="age" name="age" required><br>

        <label for="yearOfEmployment">Year of Employment:</label>
        <input type="number" id="yearOfEmployment" name="yearOfEmployment" required><br>

        <label for="hobbies">Hobbies:</label><br>
        <input type="checkbox" id="reading" name="hobbies" value="Reading">
        <label for="reading">Reading</label><br>

        <input type="checkbox" id="cooking" name="hobbies" value="Cooking">
        <label for="cooking">Cooking</label><br>

        <input type="checkbox" id="hiking" name="hobbies" value="Hiking">
        <label for="hiking">Hiking</label><br><br>

        <!-- Address section -->
        <label for="street">Street:</label>
        <input type="text" id="street" name="street" required><br>

        <label for="city">City:</label>
        <input type="text" id="city" name="city" required><br>

        <label for="country">Country:</label>
        <input type="text" id="country" name="country" required><br>

        <button type="submit">Submit</button>
    </form>

    <!--<script src="jsonbin.js"></script>-->
    <script src="jsonbin2.js"></script>
</body>
</html>

document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('userForm');

    form.addEventListener('submit', async function(event) {
        event.preventDefault(); // Prevent default form submission

        // Get form values
        const firstName = document.getElementById('firstName').value;
        const lastName = document.getElementById('lastName').value;
        const age = document.getElementById('age').value;
        const yearOfEmployment = document.getElementById('yearOfEmployment').value;
        const hobbies = getHobbies();
        const street = document.getElementById('street').value;
        const city = document.getElementById('city').value;
        const country = document.getElementById('country').value;

        // Create user object
        const newUser = {
            firstName,
            lastName,
            age,
            yearOfEmployment,
            hobbies,
            address: {
                street,
                city,
                country
            }
        };

        // Call function to update user details
        await updateUserDetails(newUser);
    });

    // Function to get selected hobbies
    function getHobbies() {
        const checkboxes = document.getElementsByName('hobbies');
        const selectedHobbies = [];
        checkboxes.forEach(function(checkbox) {
            if (checkbox.checked) {
                selectedHobbies.push(checkbox.value);
            }
        });
        return selectedHobbies;
    }

    // Function to update user details
    async function updateUserDetails(newUser) {
        const binId = 'xxaaxx'; // Replace with your bin ID
        const apiUrl = `https://api.jsonbin.io/v3/b/${binId}`;

        try {
            // Fetch existing user data
            const response = await fetch(apiUrl, {
                method: 'GET',
                headers: {
                    'X-Master-Key': 'xxxxxxxx' 
                }
            });

            if (response.ok) {
                const userData = await response.json();

                let updatedUser;
                if (userData.record) {
                    const existingUser = userData.record.data;
                    // Merge existing user data with new user data
                    updatedUser = {
                        ...existingUser,
                        ...newUser
                    };
                } else {
                    updatedUser = newUser;
                }

                // Update user details
                await fetch(apiUrl, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Master-Key': 'xxxxxxx' 
                    },
                    body: JSON.stringify({ data: updatedUser })
                });

                alert('User details updated successfully now!');
                form.reset(); // Clear the form after updating details
            } else {
                throw new Error('Failed to fetch existing user data');
            }
        } catch (error) {
            console.error(error);
            alert('Failed to update user details. Please try again later.');
        }
    }
});