Use fetched API data outside of the function

To make my code cleaner I want to use fetched API data in a few different functions, instead of one big. Even though I ‘ve did manage to reffer to that data in other functions, the problem is the API im a fetching throws different, randomized results every time it is called. And so the output from userData() does not equal that from userData2(), even though my intention is different and I’d like the result variable contents to be the same between functions.

const getData = () => fetch('https://opentdb.com/api.php?amount=10')
  .then(response => response.json());

  const useData = async () => {
  const result = await getData();
  console.log(result);
  }

  const useData2 = async () => {
    const result = await getData();
    console.log(result);
}

Wait for my files to be created. JS (express-fileupload)

Express-fileupload has a function that allows to move the .mv() file, what I am looking for is to wait for it to finish so I can proceed with the next task.

NPM: https://www.npmjs.com/package/express-fileupload

CODE

console.log("Starting the loop")
for (const element of _sources) {
  const file = req.files[element];
  if (file !== undefined) {
    const _mime = mimesList.filter((v) => v.mimetype === file.mimetype);
    if (_mime.length === 0) {
      //... exec
    } else {
      console.log("Start moving the file")
      const previewPath = _path + new tokenGenerator().generate() + element + _mime[0].extension;
      await file.mv(previewPath, function (err) {
        if (err) {
          //!make error
        }
        req.files[element].preview = previewPath;
        console.log("No errors")
      });
      console.log("I have finished moving the file.")
    }
  } else {
    //.. exec
  }
}
console.log("Ending the loop")

current output

Starting the loop
Start moving the file
I have finished moving the file.
Start moving the file
I have finished moving the file.
Start moving the file
I have finished moving the file.
Ending the loop
No errors
No errors
No errors

expected output

Starting the loop
Start moving the file
No errors
I have finished moving the file.
Start moving the file
No errors
I have finished moving the file.
Start moving the file
No errors
I have finished moving the file.
Ending the loop

Browser back button not working with react-router-dom navigate with replace true?

I have a large SPA with React and react router DOM, but in essence when you visit the path /foo, it replaces the URL with /foo?query=serializedJSON, where serializedJSON is some serialized JSON string. It does that like this:

const navigate = useNavigate();
const saveQuery = useCallback(
  (q: QueryType, analyze = true): void => {
    setQuery(q);
    navigate(`?query=${encodeURIComponent(JSON.stringify(q))}`, {
      replace: true,
    });
  },
  [navigate, setQuery]
);

So the way our app has to initially set this value, is in 3 steps:

  1. First go to /foo
  2. Then that updates query with the first chunk of data, so it’s like /foo?query=json1.
  3. Then finally it gets all the necessary JSON and updates it to the complete value, /foo?query=json2.

So when I click a link that loads /foo, it replaces the URL with /foo?query=json1 then quickly to /foo?query=json2. When I press the back button though, it is going back to /foo?query=json1? Why is that happening? I am using navigate(url, { replace: true }) in my code. Any tips on what else might be wrong would be appreciated. Unfortunately the code is scattered all around a big app, so I can’t produce an easily runnable example.

I call saveQuery the first few times in a useEffect hook, otherwise it is called on a button click.

I am trying to draw circles and add popup on a map, but i keep getting errors. Cannot read properties of undefined (reading ‘lng’)

1.This piece of code is from my App.js

  1. I am using this as the default location of the map once the app opens

    const [mapCenter, setMapCenter] = useState({lat: 34.80746, lng: -40.4796});

  2. I using this to update the location of the map, as selected from the dropdown menu, I am getting the lat and lng from data pulled from an endpoint

    setMapCenter([data.countryInfo.lat, data.countryInfo.lng]);

  3. I am passing the following props to the Map

     ```<Map center={mapCenter}
       zoom={mapZoom}
       countries={mapCountries}
       casesType={casesType}
       />```
    
  4. This is from my utils.js file, colors of the said circles according to their case types

     ```import { Circle, Popup } from "react-leaflet";
    
       const casesTypeColors = {
       cases: {
         hex: "#CC1034",
         rgb: "rgb(204, 16, 52)",
        half_op: "rgba(204, 16, 52, 0.5)",
        multiplier: 800,
         },
    
       recovered: {
        hex: "#7dd71d",
        rgb: "rgb(125, 215, 29)",
        half_op: "rgba(125, 215, 29, 0.5)",
         multiplier: 1200,
       },
         deaths: {
        hex: "#fb4443",
        rgb: "rgb(251, 68, 67)",
         half_op: "rgba(251, 68, 67, 0.5)",
        multiplier: 2000,
        },
        };```
    
  5. This is from my utilis.js. I am trying to draw the circle and popup on the map. Console error (uncaught TypeError: Cannot read properties of undefined (reading ‘lng’)

      ```export const showDataOnMap = (data, casesType = "cases") => (
        data.map((country) => ( 
        <Circle >
        center = {[country.countryInfo.lat, country.countryInfo.long]} 
    
          fillOpacity = {0.4},
         color={casesTypeColors[casesType].hex},
         fillColor={casesTypeColors[casesType].hex}, 
    
        radius={
         Math.sqrt(country[casesType]) * casesTypeColors[casesType].multiplier
       } 
        <Popup>
         <h6>Is the POPUP working</h6>
      </Popup>
      </Circle>
        ))
        );```
    

7.This is from my Map.js. Console error (uncaught TypeError: Cannot read properties of undefined (reading ‘lng’)

         ```import { showDataOnMap } from './utils';

           function Map({center, zoom, countries, casesType}) {
                return (
              <div className='map'>
      <LeafletMap center={center} zoom={zoom} scrollWheelZoom={false} >
         <TileLayer
         attribution='&copy; <a 
         href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
           />
            {showDataOnMap(countries, casesType)} 
      </LeafletMap>
                 </div>
            )
             }

             export default Map```

Why is javascript replace not working on my string? [duplicate]

Below is a Leetcode problem where I’m turning the input of Roman numbers to numbers. Once I count my larger numerals, I’d like to remove them from the string, but replace is not working. In my debugger, I can confirm that the total is being updated so the if statements are working. I can’t seem to figure out why the string is not being updated. Any ideas?

var romanToInt = function (s) {
  let total = 0
  if (s.indexOf("CM") !== -1) {
    total = total + 900
    s.replace('CM', '')
  }
  if (s.indexOf("CD") !== -1) {
    total = total + 400
    s.replace('C', '')
  }
  if (s.indexOf("XC") !== -1) {
    total = total + 90
    s.replace("XC", " ")
  }
  if (s.indexOf("XL") !== -1) {
    total = total + 40
    s.replace("XL", " ")
  }
  if (s.indexOf("IX") !== -1) {
    total = total + 9
    s.replace("IX", " ")
  }
  if (s.indexOf("IV") !== -1) {
    total = total + 4
    s.replace("IV", " ")
  }

  for (i = 0; s.length > i; i++) {

    let position = s[i]

    switch (position) {
      case 'I':
        total = total + 1
        break;
      case 'V':
        total = total + 5
        break
      case 'X':
        total = total + 10
        break;
      case 'L':
        total = total + 50
        break;
      case 'C':
        total = total + 100
        break;
      case 'D':
        total = total + 500
        break;
      case 'M':
        total = total + 1000
        break;
      default:
        total = total + 0;
    }
  }

  return total
};

How to remove ONLY undefined and null values from an object with lodash

Say I have an object that looks like this:

const obj = {a:1, b:2, c:'hello', d:undefined, e:null, f:0}

How do I filter only undefined and null and not just falsey values from the object so the resulting object will look like:

const obj = {a:1, b:2, c:'hello', f:0}

I have tried using the following lodash functions:

_.pickBy(obj, _.identity)
_.pickBy(obj, _.isNil)

But they all filter out only the falsey values.
How do I achieve this with lodash.

Setting and unsetting element style, with clicks

So, im trying to make some sort of task list.

I append list items by pressing the enter button and by filling an input.

I now want to add a feature, by which, whenever i click on a task, it gets marked with a line,
and then with a followup click, the line gets removed. This should be done repeatedly.

However, with my code, i can only do that once per list item. So, after i remove the line, i cant click on it and reapply the line style and then do it all over again.

I am guessing this block of code has to be outside, as a seperate block of code.

HTML

<body>
  <div>
    <input id="things">
        <ul id="list">
        </ul>
    </div>
</body>

JS

const things=document.querySelector('#things');
things.addEventListener("keyup", function(event) {
    const li = document.createElement("li");
    if(event.keyCode === 13){
        li.innerHTML = things.value;
        document.querySelector("#list").appendChild(li);
        // txtInput.value = "";
    } 
    li.addEventListener("click", function() {
        li.setAttribute("style","text-decoration: line-through");
        li.addEventListener("click", function() {
            li.setAttribute("style","text-decoration: none");
        });
    });
});

http://jsfiddle.net/65s4yv0z/5/

Error: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method

Getting an error on the below function that is triggered on a button click. It will load correctly but the error causes other javascript elements to display incorrectly when opened.

function showSSMVirtual() {



 // Clear the container for the SSM app 
 $('#ssmDiv').empty();

 // Add in a close control

 $('#ssmDiv').append('<a class="ssmCloseNav" href="javascript: closeSSMVirtual();">X</a>');

 // Add in the SSM app

 $.get('/api/SMdetail', function (details) {

    if (details) {

        var fname = details.FirstName;
        var lname = details.LastName;
        var source = details.Source;
        var token = details.BearerToken;
        var env = details.Enviroment;

        $('#ssmDiv').append('<app-ssm fname=' + fname + ' lname=' + lname + ' source=' + source + ' token=' + token + ' env=' + env + '  id="sm-ma"></app-ssm>');

        // Show the container area 

        $('#ssmDiv').show();

    }

 });

}

Compare two cells in a html table and highlight row if different

I have an HTML table (tree table precisely but it doesn’t matter) and it has several columns. For each row, it is very important that the values in one of the columns should be higher than the other column. If that is not the case then I’d like to highlight that entire row. How do I do that?

My HTML code looks like this:

<table id="stepstats-list-exp"> 
      <thead>
        <tr>
          <th> name   </th>
          <th> elp_01  </th>
          <th> elp_20  </th>
          <th> scal </th>
        </tr>
      </thead>
      <tbody>
        <tr data-tt-id=864845 data-tt-parent-id=>
          <td> &#39;Init&#39; </td>
          <td class="elp_01">  0 </td>
          <td class="elp_20"> 0 </td>
          <td class="scal"> 0.00 </td>
        </tr>
        
        <tr data-tt-id=864846 data-tt-parent-id=864845>
          <td> &#39;Update&#39; </td>
          <td class="elp_01">  0 </td>
          <td class="elp_20"> 0 </td>
          <td class="scal"> 0.00 </td>
        </tr>
        
        <tr data-tt-id=864847 data-tt-parent-id=>
          <td> &#39;Load&#39; </td>
          <td class="elp_01">  32 </td>
          <td class="elp_20"> 31 </td>
          <td class="scal"> 1.03 </td>
        </tr>
       </tbody>
    </table>

In all my test cases, elp_20 should always be smaller than elp_01. If not, the entire row needs to be highlighted. For that purpose, I have this jQuery code that doesn’t seem to be working. For each tr row, I’m checking each td column and comparing values.

<script type="text/javascript">
    /* Highlight row if elp_20 > elp_01 */
    $(document).ready(function () {
      $("#stepstats-list-exp tr").each(function () {
        $(this).find('td').each(function(){
          if (parseInt($(".elp_20").text(), 10) < parseInt($(".elp_01").text(), 10)) { 
            $(this).parent("tr").css('background-color', 'crimson');
            $(this).parent("tr").css('font-weight','bold');
            $(this).parent("tr").css('color','white');
          }
        });
      });
    });
    </script>

Repeat script until conditions are met

I have a google sheet with a timer set for 5am and everyday I want the sheet to:

  1. Refresh, which includes some links to external data, so I add a 10 second pause. There are approximately 100 rows.
  2. I successfully wrote a formula in column U to tell me if data is imported correctly, and if not it returns the text “ERROR”.
  3. Search for “ERROR” in column U.
  4. If there are any “ERRORS” in column U, refresh the page again and wait 10 seconds.
  5. Repeat until there are no “ERRORS”
  6. Only when there are no “ERRORS” in column U, copy the values in column V and paste-values in column W.

I think I am close… I just can’t figure out how to tell it to re-run the “IF” portion if still finds “ERRORS”. Any input is appreciated!

Here is a link to the file -> https://docs.google.com/spreadsheets/d/1GFN3tXRlqxo9J9iNpZMPk-e-WlNGVjJ4zSqZ1_aEE_U

  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Players'), true);
  
  SpreadsheetApp.flush();
  Utilities.sleep(10000);
  
  var findVal = spreadsheet.getRange('U:U').getValue()
  if(findVal.match('ERROR')){
  
  SpreadsheetApp.flush();
  Utilities.sleep(10000)}
  
  else{
  spreadsheet.getRange('W:W').activate();
  spreadsheet.getRange('V:V').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);}
}```

javascript replace by regex match location

In this program I want to replace the 2 + in str respectively by array element. The solution below doesn’t work because the regex contains + and the array contains also +. How to do that kind of replacement by location then ?

let regex = /+/gm;
let str = `abc+def+`;
let array = ["+", "test"];
let matches = [...str.matchAll(regex)][0];
for (let a of array.entries()) {
  console.log(a);
  str = str.replace(/+/, a.toString())
  console.log(str);
}

React Native – Navigation.navigate() only works within an onPress function

In my app,

onPress={() => navigation.navigate('<ScreenName>')} 

works flawlessly, while if I try to change the screen within a function called when I tap a button, for example

const signup = (mobileNumber, {navigation}) => {
Object.keys(mobileNumber).forEach((key) => {
    console.log(mobileNumber[key]);
});

if (mobileNumber.mobileNumber == null) {
    Alert.alert("Oops!", "Please insert your mobile number.");
    return;
}

let dataToSend = {mobile_number: mobileNumber.mobileNumber};
let formBody = [];
for (let key in dataToSend) {
    let encodedKey = encodeURIComponent(key);
    let encodedValue = encodeURIComponent(dataToSend[key]);
    formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');

fetch('https://mywebsite.com/api/v1/createAccount.php', {
    method: 'POST',
    body: formBody,
    headers: {
    //Header Defination
    'Content-Type':
    'application/x-www-form-urlencoded;charset=UTF-8',
    },
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === 'success') {
    //Alert.alert("Excellent!", "Please go on");
    navigation.navigate('<ScreenName>');
} else {
    console.log('Please check your mobileNumber');
}
})
.catch((error) => {
//Hide Loader
console.error(error);
});
}


function JoinScreen({ navigation }) {
const [mobileNumber, setMobileNumber] = useState(null);
const [isLoading, setLoading] = useState(true);

const [data, newData] = useState(null);

useEffect(() => {
    fetch("https://mywebsite.com/api/v1/createAccount.php")
        .then((response) => response.text())
        .then((response) => newData(response));
}, []);

return (
    <>
        <StatusBar hidden />
        <SafeAreaView style={{ flex: 1, alignItems: 'center', backgroundColor: '#262423' }}>

            <TextInput
                style={styles.input}
                placeholder="Your mobile number"
                placeholderTextColor="#fff"
                autoCapitalize="none"
                autoCorrect={false}
                onChangeText={(val) => setMobileNumber(val)}
                keyboardType="phone-pad"
            />

            <TouchableOpacity onPress={() => signup({ mobileNumber })}>
                <Text style={{ textAlign: "center", paddingTop: 20, color: "#babf26", fontSize: 20 }} >Create account</Text>
            </TouchableOpacity>
        </SafeAreaView>
    </>
);

}

The app returns “TypeError: undefined is not an object (evaluating ‘_ref6.navigation’)“

If can be helpful, if in the “signup” function I don’t wrap “navigation” within curly brackets, I get “undefined is not an object (evaluating ‘navigation.navigate’)“

Keep checkbox unchecked after submit

<form name="test" method="post">
    <input onchange="this.form.submit()" checked name="box1" type="checkbox">
    <input onchange="this.form.submit()" checked name="box2" type="checkbox">
</form>

How can I keep the checkbox checked/unchecked after submitting the form ?

How to get specific parts of a nested array?

I’m building a request object in front. This object consists of a string and a list of objects. Something like this

MainPricing:
{
    GlobalDescription: "test global comment"
    ListOfParticipants:
    {
        P1: {Headers: Array(9), Comment: 'HELLO p1', Pricings: Array(11)}
        P2: {Headers: Array(2), Comment: 'HELLO p2', Pricings: Array(3)}
        P3: {Headers: Array(9), Comment: 'HELLO p3', Pricings: Array(7)}
    }
}

In the backend, this translates to this C# object

public class RequestObject : MainRequest
{
    public string GlobalComment { get; set; }
    public SomeObject Pricings { get; set; }
}

js file

var request = {
    globalComment: self.globalComment(),
    mainPricings: self.mainPricings() //this includes the JSON data displayed above
};

In JS file, instead of calling self.mainPricings() and passing whole object, I am trying to pass only “Comment” part and Also several properties from Pricings. How can I achieve that?

How can I return the value of a promise? [duplicate]

I have the following funcitons. The init function has to return a IUser object for my useReducer hook, but all I get is the initial state that is passed to the init function. How can I return the loaded user here?

async function getUserFromStorage() {
  let user = {name: '', jwt: ''};
  try {
    const savedUser = await AsyncStorage.getItem('@user');
    if (savedUser) {
      user = JSON.parse(savedUser);
      return user;
    }
    return user;
  } catch (e) {
    throw Error('could not get user from local storage');
  }
}

//user passed here is an empty user object
function init(user: IUser): IUser {
  getUserFromStorage().then(state => {
    // holds the saved user data
    user = state;
  });
  //returns the passed in emtpy user object
  return user;
}