Javascript: How to set value of variable from callback? [duplicate] - javascript

This question already has answers here:
How can I access the value of a promise?
(14 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
Consider this scenario:
function myfunc() {
var total = 0;
const [ hooka, setHooka ] = useState([]);
const fetchData = () => {
api.get().then((data) => {
total = data.total;
setHooka(data.value);
}
}
return (
<h1>{total}</h1>
);
}
But the total inside the callback scope is different to the one defined in myfunc scope.
How can I set value of total in myfunc scope within the callback?
PS: It is a react hook in actual. Thank you TJ Crowder for the comment. And I've used total = data before a useState trigger method. I can use total as a hook also. But Doesn't creating more hooks slow down rendering in react or what?

Related

undefine variable Displayed when implement below code [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 months ago.
undefine variable will loadData function from displayStructure all variables names, ages..etc displayed
async function loadData(route) {
const response = await fetch('http://127.0.0.1:8000/'+route);
const names =await response.json();
console.log(names);
return names;
}
function displayStructure(){
var names=loadNames('getNames');
var department=loadNames('getDep');
var ages=loadNames('getAge');
var bod=loadNames('getbod');
}

How to get a value outside of a firebase callback? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why Does Firebase Lose Reference outside the once() Function?
(2 answers)
returning array after finish reading from Firebase
(1 answer)
Closed 1 year ago.
I guess this is not a Firebase question as much as it is a callback syntax question:
I want the function changeName to go to Firebase database and replace the value of "t" with a value that is a child of "t" in the database.
function changeName (t) {
return (
t.replace(t, firebase.database().ref(`langs/${t}`).once('value', snap => snap.val().name))
)
}
But I get [object Promise].
The code does work when I put an alert() method inside the snap arrow function, so I know the access to the value is fine. I just couldn't figure out how to get the value as a string of text for the replace() method.
This should work
function changeName (t) {
return (
firebase.database().ref(`langs/${t}`).once('value', snap => {
t.replace(t, snap.val().name);
})
)
}

Object has contents, as long as I don't want to specifically adress them [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Console.log showing only the updated version of the object printed
(3 answers)
Closed 2 years ago.
I have this React project, in which I fetch data from a firebase database and construct a object called "statehelp" from the results. Now for some reason, if I console log the whole statehelp Object I get all its contents, however if I want to access statehelp.contents or statehelp.products they are undefined.
componentDidMount() {
var statehelp = {
content: {},
products: {}
}
getFarm(this.id).then(result => statehelp.content = result)
getProduct(this.id).then(result => statehelp.products = result)
console.log(statehelp)
console.log(statehelp.content)
}
That happens because console.log() is synchronous operation. It won't wait for your api call to happen. So don't use console.log() as a metric for identifying whether your object got populated or not.

javascript boolean variable's value is not changing [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a variable called itemExist and set that equal to false. My goal is to set this variable's value to true if a condition happens. My code is this:
var itemExist = false;
user.findById({_id: decoded._id}).populate('shoppingCart').exec((err, items)=>{
items.shoppingCart.forEach(async item=>{
if(item.productId == productId){
itemExist = true;
When I console log the itemExist variable outside of all theese functions
console.log(itemExist);
I get that result on the console:
false
But it should be true. How can I solve this problem, what is causing that?
Perform your work inside exec function
user.findById({_id: decoded._id}).populate('shoppingCart').exec((err, items)=>
{
const itemInArr = items.shoppingCart.find(item => item.productId === productId);
//!! - convertation to boolead value
itemExist = !!itemInArr;
console.log(itemExist);
}
);

Why can't I return this function using this specific method? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
I have a function, which contains a sub function. I need to return a variable from the sub function however I am not sure how (I am new to JS).
I also want to avoid using a global variable, as I have about 15 more functions similar to this.
It shows the error, x is not defined.
return data.rr_vin
^
ReferenceError: data is not defined
I have tried declaring the variable as an attribute of the function, i.e. function.myvar, however I still get the same issue.
function find_num() {
fetch("somefile.json")
.then(res => res.json())
.then(data => {
a = data.numdata.filter(el => el.Process==="Process1").map(o => o.Finish_Time);
b = recent_time(a)
data.x= Math.max(data.numdata.filter(el => el.Finish_Time===b).map(o => o.Shortnum));
console.log(data.x)
return data.x
})
return data.x
}
Ideally I want to call on the find_num() function to return x.

Categories

Resources