Let vs Var with AsyncStorage Strange Exception [duplicate] - javascript

This question already has answers here:
Cannot use let to define a variable with the same name of function's parameter
(2 answers)
Javascript ES6 'let' and 'var' - unexpected behavior inside function with argument name matching redeclared variable
(1 answer)
Closed 3 years ago.
To replicate the below, run this code on React Native 0.59.8
I have a function that looks like the below:
import AsyncStorage from 'react-native';
const saveToStorage = async (value) => {
await AsyncStorage.setItem('#store.key', value);
let value = await AsyncStorage.getItem('#store.key');
// Exception is thrown on ios because value is seen as null
}
But if I changed let to var the request is processed successfully.
const saveToStorage = async (value) => {
await AsyncStorage.setItem('#store.key', value);
var value = await AsyncStorage.getItem('#store.key');
// No exception is thrown on ios
}
Does anyone have an idea what is going on?

I would comment this if I could but I think there's a couple things that you could change. Don't name that variable value because you are passing a parameter called value into your async function, so value will already be defined. Also I think you are missing an await in your AsyncStorage.getItem('#store.key')

Related

A variable inside async function derived from a promise has different value when returned to global scope [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I do not understand why the query variable has a value inside async function that changes when returned and declared in the global environment. I want to return the value from my database to a global variable outside of the async function.
What is the logically reason this happens. How do I extract the integer value from the Promise {1}.
async function glob(){
var result = await knex.raw('select max(glob) from or');
let query = await result.rows[0].max ;
console.log(query);
return query ;
}
let go = glob();
setTimeout(()=>{console.log(go)},1000);
setTimeout(()=>{console.log(go == 1)},1000);
The console returns.
1
Promise { 1 }
false

concatenating 2 arrays unexpected result [duplicate]

This question already has answers here:
React hooks stale state
(1 answer)
State not updating when using React state hook within setInterval
(14 answers)
Wrong React hooks behaviour with event listener
(9 answers)
Closed 1 year ago.
I am trying to update my array state with a list of records I am getting from an API, I am trying it as follows:
const [record, setRecord] = useState([])
const addRecords= async ()=>{
const apiResult = await apicall()
setRecord(record.length ? [...apiResult, ...record] : apiResult)
}
however every time the api is called is overwritting my 'record' with the last items added from the api instead of putting them together.
I also tried using .concat() with same result
const addRecords=async()=>{
const apiResult = await apicall()
setRecord(record.concat(apiResult ? apiResult:[])
}
there is sth here I am not managing to understand, hope someone can clarify what can it be.
I think you want to use a function in your setter to get your previous value (I dont understand enough to give you the reason why, but I think it has something to do with your record being a frame or two out of date)
const addRecords=async()=>{
const apiResult = await apicall()
//prevRecord is more recent than record (I think)
setRecord(prevRecord=>prevRecord.concat(apiResult || [])
}

Typescript syntax: calling a function with < > [duplicate]

This question already has answers here:
Rules for the use of angle brackets in TypeScript
(2 answers)
Closed 3 years ago.
I have just seen a piece of code for React that has a syntax I have never seen before. I haven't been able to find what it actualy is. Can someone, please, explain what calling a function with <> instead of () does?
const ConfirmationServiceContext = React.createContext<
// we will pass the openning dialog function directly to consumers
(options: ConfirmationOptions) => Promise<void>
>(Promise.reject);
The piece of code is from here
This is actually Typescript type firm for an async lamda.
React.createContext<(options: ConfirmationOptions) => Promise<void>>(Promise.reject);
React.createContext is a Generic type, the < and > is how we pass the concrete type we're going to use in this instance. Here we're passing an inline function that gets a ConfirmationOptions object and returns a Promise whose value is void

What is the difference between var {todo}= require("./models/todo"); and var todo=require("./models/todo"); [duplicate]

This question already has answers here:
Curly brackets (braces) in Node.js 'require' statement
(2 answers)
Closed 3 years ago.
I am trying to load a todo model from my todo class and I have two options. The first one is
var {todo}= require("./models/todo");
and second one is
var todo=require("./models/todo");
I am confused which is what.
The first one is a destructuring assignment. It means "take an object from "models/todo" and assign its property "todo" to my local variable "todo". If it contains no such property, you'll get undefined assigned to the variable.
For example this if is your model
module.exports = {
toLower: obj => {
},
streamIdea: async (idea) => {
}
}
if you're doing this
const model = require('mymodel');
then you have to call your functions like this,
model.toLower()
which means you're importing everything and calling it by function name
and if you're importing like this:
const { toLower } = require('mymodel');
it means you're only importing toLower from this model now you can just call it like this
toLower();
without need of model.

returning a value from async/await promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to find a simple example of how to return a value from async/await where the value is easily accessed outside the async function.
Would the following two examples be considered the optimum way to return a value from an async/await function?
In other words, if the value returned from an async/await needs to be saved and used in other parts of the code, what would be the best way to save the value?
this is the easiest example i could find:
async function f() {
return 1;
}
var returnedValue = null; // variable to hold promise result
f().then( (result) => returnedValue = result );
console.log(returnedValue); // 1
or perhaps would it be better to use an object?
async function f(varInput) {
varInput.value = 1;
}
myObject = {} ; myObject.value=null;
f(myObject);
console.log(myObject.value); // 1
thank you.
My answer addresses two subjects here:
1) Async function returns a promise that resolves to a value. So, for instance your first function can be used as per your example. It can also be used like this:
async function() {
const x = await f();
}
2) Immutability - the second solution will work but it makes your funciton "impure". It is not bad in itself, but beware of side effects this might cause (for instance, if you change an app-wide singleton value without other components being notified about it, some part of your app might go out of sync with the data).
Hope this answers your question.

Categories