Search code examples
reactjsscopeglobal-variableslocal-variables

Change arrow function to use var globally


I'm using findNearest to calculate my distance to an array of points (and it returns the closest one) and then I'm calculating the distance to that point.

It works but the way I did it does not allow me to use the "found" var globally, only inside the arrow function as a local variable.

I read about transforming it, I tried to follow guides, I tried to declare it outside the function but I can´t seem to get it right.

var mK = [
    { latitude: -34.906874, longitude: -56.206150 },   //  Globally declared
    { latitude: -34.888571, longitude: -56.191530 },
    { latitude: -34.880967, longitude: -56.163187 },
    { latitude: -34.895048, longitude: -56.155973 },
    { latitude: -34.911097, longitude: -56.133299 },
    { latitude: -34.920388, longitude: -56.146530 },
   ];

const finder = () => {
  var firstfind = findNearest({ latitude: coords.latitude, longitude: coords.longitude }, mK);

var found = getPreciseDistance(
    { latitude: coords.latitude, longitude: coords.longitude },
    { latitude: firstfind.latitude, longitude: firstfind.longitude }
);
   console.log(found)
   alert( JSON.stringify(found));
}
                             //I can't use var "found" in my js

Solution

  • Just because you declare a variable outside of the scope of a function doesn't mean you can use it outside of that file in React. You have to export it for it to be available externally.

    export var found = getPreciseDistance(
        { latitude: coords.latitude, longitude: coords.longitude },
        { latitude: firstfind.latitude, longitude: firstfind.longitude }
    );