This question already has answers here:
Console.log showing only the updated version of the object printed
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm retrieving data from api and storing it in a sharedState. When i'm trying to access this data like below it seems to return the correct. There is one object in the dashboard array with name field.
console.log(newState.profile)
returns:
However when i access dashboards
console.log(newState.profile.dashboards)
it returns
[]
function to set the state from main.js
export function getProfile(state, user) {
const newState = Object.assign({}, state);
if (user) {
db().collection("users").doc(user.uid)
.onSnapshot((doc) => {
var data = doc.data()
if (data) {
newState.profile.apps = data.apps
newState.profile.dashboards = data.dashboards
} else {
authservice.setUserAcc(user.uid)
}
});
}
return newState
}
i'm not sure wether this is a javascript behaviour or related to the way i did set up the state.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am trying to change the values of variables within a useEffect call in js React.
I notice that the values get changed inside of the function, but the global value is not changed.
var O_name = "";
var A_name = "";
var A_platform = "";
var C_name = "";
function Statsview( {backButton} ) {
const urlParams = new URLSearchParams(window.location.search);
const name = urlParams.get('name');
var data = useRef();
const [overwatchName, setO_Name] = useState([]);
useEffect(() => {
console.log('mounted')
database.collection('USERS').where('name','==',name).get().then(snapshot => {
snapshot.forEach(doc => {
var data = doc.data()
O_name = data.overwatch;
console.log(O_name)
A_name = data.apexLegends;
console.log(A_name)
A_platform = data.apexLegendsPlatform;
console.log(A_platform)
C_name = data.chess;
console.log(C_name)
})
}).catch(error => console.log(error))
},[]);
console.log("oname: ",O_name)
console.log("aname: ",A_name)
console.log("aplat: ",A_platform)
console.log("cname: ",C_name)
...
...
}
The console logs inside of the useEffect show updated values for each varaible.
However, the console logs outside of the useEffect show that the values for each variable are blank.
How do I change these global values?
Global variables and functions are initiated when React first load all the scripts, that means when you first load (or reload) the page. React itself is not aware of the mutation of these global variables.
Your code flow is like this.
Global variables are initialized.
console.log() prints the content when a component is loaded.
An async call mutates the global variables => React is not aware of them. hence does not re-render your component. Hence, console.log() is not called.
You should use state hook to store these variables so React knows they are changed.
You should use useRef for this case.
so for simple example.
function MyComponent(){
const A_name = useRef('');
useEffect(() => {
A_name.current = 'new value'
}, []);
}
You can change/access the variable with .current property
You can read more at docs here: https://reactjs.org/docs/hooks-reference.html#useref
It mentioned: useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
So it would fit your objective
This question already has answers here:
React setState not updating state
(11 answers)
Closed 2 years ago.
let [amount, setAmount] = React.useState(100);
function ChangeHandler(event) {
let value = event.target.value;
setAmount(value);
props.update(amount);
}
props.update is a function that I passed from a higher component to update another Hook.
You can't access the state after setting it in next line.
do it like that
let [amount, setAmount] = React.useState(100);
function ChangeHandler(event) {
let value = event.target.value;
setAmount(value);
props.update(value);
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have component in my angular 5 project, bill-page. On bill-page I get some info, bill and currency. It is two arrays, bill (array with one object, get it from my firebase) and currency (array with two objects, get it from free api). When I wanna chek this arrays by using
console.log()
it shows me that is two normal arrays with some objects.
export class BillPageComponent implements OnInit {
currency: any = [];
bill: any = [];
userId: string;
isLoaded = false;
copyCurrency: any = [];
constructor(private billService: BillService, private authService: AuthService) {}
ngOnInit() {
this.isLoaded = false;
this.userId = this.authService.returnAuthState();
this.billService.getBillFirebase(this.userId).subscribe(
(resp)=>{
for (let key in resp) {this.bill.push(resp[key])}
}
);
console.log(this.bill);//[{currency: "USD", value: 0}]
this.billService.getCurrencyPB().subscribe((data)=>{
this.currency.push(data[0]);
this.currency.push(data[1]);
});
console.log(this.currency); //[{key1:1, key2:2},{key3:3, key4:4}]
this.isLoaded = true;
}
But when I try get this objects from arrays, or property from objects it becomes undefined, for example
console.log(this.bill[0])// undefined or console.log(this.bill[0].value)//undefined
or if I try copy this arrays it becomes undefined too
this.copyCurrency = this.currency.slice();
console.log(this.copyCurrency) // undefined
Basically what happened was that it executed aysnchronously. console.log (this.bill) executed before it got any value. this.bill gets the value only inside the subscribe function.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
export class myclass implements OnInit {
private outagesList;
private outageArray;
constructor(private outages: OutagesService){}
ngOnInit(){
this.outages.getOutagesList().subscribe((data) => {
this.outagesList = data;
this.outagesList.forEach( function (arrayItem)
{
this.outageArray.push(arrayItem["title"]);
});
)
}
If i try to push the data into outageArray it is throwing ERROR TypeError: Cannot read property 'outageArray' of undefined
How can i avoid this error? I need to access this outageArray value to html.
Use an arrow function
this.outagesList.forEach((arrayItem) => {
this.outageArray.push(arrayItem["title"]);
});
Once you are using post-ES6 Javascript, functions like forEach are not likely to be your best solution. The easiest way to do this is with a for..of loop:
this.outages.getOutagesList().subscribe((data) => {
this.outagesList = data;
for (let arrayItem of this.outagesList)
{
this.outageArray.push(arrayItem.title);
});
)
This question already has answers here:
How can I add a key/value pair to a JavaScript object?
(26 answers)
Closed 8 years ago.
I have a function like this:
function dataSend(type, message) {
return {
type: message
};
};
Which I am using like this:
io.sockets.emit('addToQueue', dataSend('error', 'User not found'));
But when it gets to the client side I get an object that is like
{ type: 'User not found' }
instead of
{ 'error': 'User not found' }
Why is this acting like this? I'm not sure how to fix this any information would be great thanks.
You can't set the key with a variable like that, you'll need bracket notation
function dataSend(type, message) {
var obj = {};
obj[type] = message;
return obj;
};
Try this:
function dataSend(type, message) {
var a={};
a[type]=message;
return a;
}
Javascript doesn't require quotes around the property names.
Using {type:message} or {'type':message} produces the same result.