Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component:

    const [currentGPS, setCurrentGPS] =
            useState({coords:{latitude:0.0,longitude:0.0}})

    useEffect(() => {
      utl.getGPSLocation(
        (v:{coords: {latitude:number; longitude:number;};})=>
        setCurrentGPS(v))
    }, [])

Whenever I try to use the following function:

    function getGPSLocation({callBackFn}:
      {callBackFn:
        (v:{coords: {latitude:number; longitude:number;};}) => void
      }) {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position: {coords: {latitude:number; longitude:number;};}) => {
            callBackFn(position)
            console.log('(U)position.coords.latitude='+JSON.stringify(position.coords.latitude))
            console.log('(U)position.coords.longitude='+JSON.stringify(position.coords.longitude))
          });
      } else {
        console.log("Geolocation is not supported by this browser.");
      }
    } /* End of getGPSLocation */

An error message appears in the Web Developer Tools console of my web browser:

Uncaught TypeError: t is not a function
NextJS 10
page-1aeb39b39d44f814.js:1:332

The error seems to be related to this line of code:

    callBackFn(position)

If I remove that line, the expected output is displayed:

(U)position.coords.latitude=25.515932844138406 page-2bc533c4f68ab71b.js:1:339
(U)position.coords.longitude=67.32855152591916 page-2bc533c4f68ab71b.js:1:417

Why am I getting this error? And what could be the solution?

I require assistance in properly passing setCurrentGPS (as a callback) to the getGPSLocation function.

Answer №1

getGPSLocation function requires an object with callBackFn key as an argument. To update your useEffect, you can do the following:

useEffect(() => {
  utl.getGPSLocation({
    callBackFn: (v: { coords: { latitude: number; longitude: number } }) =>
      setCurrentGPS(v)
  });
}, []);

Alternatively, you have the option to modify the function definition:

function getGPSLocation(
  callBackFn: (v: { coords: { latitude: number; longitude: number } }) => void
) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position: { coords: { latitude: number; longitude: number } }) => {
        callBackFn(position);
        console.log('(U)position.coords.latitude=' + JSON.stringify(position.coords.latitude));
        console.log('(U)position.coords.longitude=' + JSON.stringify(position.coords.longitude));
      });
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Firefox, there is a peculiar issue where one of the text boxes in an HTML form does not display

In my HTML form, users can input their first name, last name, and phone number to create an account ID. The textboxes for first name, last name, and account ID work smoothly on all browsers except Firefox. Surprisingly, the phone number textbox doesn' ...

Is the Spring MVC ModelAndView object being returned?

After clicking a link on a jsp page, I have a GET method that is instantiated as: HTML: <div class="panel accordion clearfix" id="dispdir"> <script type="text/javascript"> window.onload = function() { //showDirectorySe ...

Retrieving the data from a Material UI Slider control

I'm encountering an issue with retrieving the value property I assigned to a component. event.target.value is returning undefined. How can I successfully access the value of the component? My goal is for handlePlayersChange() to be able to handle dyn ...

Angular's watch feature fails to trigger when the value is modified

My setup includes two sliders, one for brightness and the other for contrast. They are linked to a "brightness" model and a "contrast" model. These sliders are located within a tab interface, and I noticed that every time the tab was changed, the values we ...

Tips for creating a customized dropdown menu that opens upwards without relying on Bootstrap

Looking for some assistance with creating an animated dropdown menu that slides upwards. Any help is appreciated! $('.need-help').click(function() { $('.need_help_dropdown').slideToggle(); }); .need-help { background:url(../im ...

Return a potential undefined output

I am working with a variable called root which could potentially be undefined. Its value is only determined at runtime. const root = resolvedRoot || await this.fileSystem.getCurrentUserHome(); console.log('root.uri = ' + root.uri); The existenc ...

Error: webpack is failing to load the style and CSS loaders

I'm currently experimenting with the FullCalendar plugin from fullcalendar.io. They recommended using Webpack as a build system, which is new to me. I managed to set up the calendar functionality after some research, but I'm facing issues with th ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

Safari experiences occasional failures with pre-signed post uploads to S3 when using multipart/form-data for file uploads

Lately, I've encountered issues with pre-signed post uploads to S3 that seem to be unique to Mobile Safari browsers. Interestingly, the error has also shown up occasionally on Desktop Safari. Whenever this error occurs, it triggers a response from S3 ...

Error message: Cannot bring in JavaScript category. TypeError: "class" does not work as a constructor

I'm encountering a strange problem when trying to import my class into another module. Everything works fine when I import the worker module in my start.js file and run the script smoothly. But, the issue arises when the socket module attempts to impo ...

Sending non-textual data within a JQuery ajax POST request

I have encountered an issue related to sending data from a JavaScript application to a Node.js server for database query purposes. Despite trying to find a solution from various sources, I have been unable to resolve it. Here is the code snippet used to s ...

Converting JS carousel to TS for showcasing multiple items

I am currently working on integrating a bootstrap carousel into my Angular project and I need to convert my JavaScript file to a TypeScript file. As someone who is new to this, I'm unsure of the process for converting and implementing it in a .ts file ...

The Data Table experiences intermittent hanging issues (Table is empty) when sorting or loading data with Knockout binding

While working on a project, I encountered an issue with binding data to a table using Knockout JS and the JQuery/Bootstrap based; Data Table API. The problem was that the table would become unresponsive at times when sorted or loaded, without any errors be ...

Improving the efficiency and readability of JavaScript syntax (specifically conditional statements with if-else) in Vue.js

Seeking advice on optimizing and simplifying this syntax in Vue's methods section: methods: { getColorBtn(status, isCorrect, isRemind, textButton) { if (status === 1 && isCorrect === 1 && isRemind === 1) return 'v-btn--outlined theme--l ...

Implementing a return of a view from a Laravel controller function after an AJAX request

I'm currently working on a bookstore project where users can add books to their cart. Users have the option to select multiple books and add them to the cart. When the user clicks on the Add to Cart button, I store the IDs of the selected books in a J ...

The .NET controller does not receive traffic for the GET method

Having some trouble populating a table with JSON data using angular ng-repeat. No errors are showing up in the console, and my breakpoint in the .NET Controller isn't being triggered. Here's the code for the App Controller: var app = angular.mo ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

Angular 4: Triggering a function by clicking a link with specific parameters

I am relatively new to working with Angular 4. I have an anchor tag that, when clicked, should redirect me to a link where I also need to pass parameters. I'm unsure if my current approach is correct or not. Above all, I really need guidance on how to ...

Finding results in AngularJS by typing at least 4 characters into the input field

I am using a MySQL database to search with AngularJS. How can I set it up so that the search only triggers when at least 4 characters are inputted? Here is the HTML code: <div class="search"> <form action="" method="post" class="searchform" &g ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...