Listen to js variable change
You can create a listener for the variable change using setTimeout
, something like:
let place2IsReady = false;
setReadyListener();
// testing wait 2 seconds to set place2IsReady to true
// so: an alert should occur after 2 seconds
setTimeout(() => place2IsReady = true, 2000);
function setReadyListener() {
const readyListener = () => {
if (place2IsReady) {
return alert("Ready!");
}
return setTimeout(readyListener, 250);
};
readyListener();
}
Listening for variable value change in JavaScript
You can use the Observable pattern
Read the theory here
and you can use already built solutions to this like RxJS's observer
How to listen to external variable changes in React
Option 1
:
If you want to know when userId is filled in sessionStorage:- Add
userId
in your component state. - Listen for the
storage
event. See StorageEvent - Add userId as dependency in
useEffect
.
const getUserId = ()=> sessionStorage.getItem("userId");
const [userId, setUserId] = useState(getUserId());
useEffect(() => {
const storage = (event) => {
if(event.originalEvent.storageArea===sessionStorage){
const data = getUserId();
if(data) setUserId(data);
}
};
window.addEventListener("storage", storage);
return ()=> window.removeEventListener("storage", storage)
}, []);
useEffect(() => {
getActiveGames();
if (token && userId) {
getCart();
getWallet();
getWalletPayments();
}
}, [userId]);
Option 2:
You can manage the userId
using Context
- In
getUserId
returndata.userId
.
const UserContext = React.createContext();
const UserProvider = ({children}) => {
const [userId, setUserId] = useState(null);
useEffect(()=> {
getUserId()
.then(user => setUserId(user));
}, []);
return <UserContext.Provider value={userId}>
{children}
</UserContext.Provider>
}
In you App.js
return (<UserProvider>
...
</UserProvider)
Using userId from any component in your app:
const userId = useContext(UserContext);
useEffect(() => {
getActiveGames();
if (token && userId) {
getCart();
getWallet();
getWalletPayments();
}
}, [userId]);
See what the variable is on a variable change with js?
In a browser like Chrome or Firefox (firebug) you could run the program step by step, inspect the value, etc...
Besides, you cannot force Javascript to trigger an event when x changes.
However you could make a function (setx), having x global, or having setx a nested function within a function where x is defined:
function setx(v) {
alert("x changes!");
x = v;
}
Then instead of doing
x = 7;
you do
setx(7);
and the alert is triggered. Replace all x assignments with a call to setx and you'll be notified whenever x changes, ie whenever setx is called.
This is of course basic cross-browser JS.
How can I listen for a Service variable change in a component in Angular
You would want to add a Subject
inside your Appraisal-summary.service.ts
like this:
import { Subject } from 'rxjs';
...
export class AppraisalSummaryService {
// I am guessing scores is an array of type number
public scoreSubject = new Subject<number[]>();
calc(appraisal) {
...
//a 'scores' array is created (synchronously)
this.scoreSubject.next(this.scores); //emit the scores result
return this.scores;
}
}
And, in your other component, inside your ngOnInit
, you want to listen to this result:
import { Subscription } from 'rxjs';
....
export class YourOtherComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private appraisalSummaryService: AppraisalSummaryService) {}
public ngOnInit(): void {
// you store your subscribe
this.subscription = this.appraisalSummaryService.subscribe((scores: number[]) => {
console.log(scores);
});
}
public onDestroy(): void {
// you need this in order to avoid a memory leak
this.subscription.unsubscribe();
}
}
```
Listening to real variable changes in Javascript
Yes shure, simply compare the new to the stored value:
var obj = (function(){
let store = undefined;
return {
get value() {
return store;
},
set value(v){
if(v !== store){
alert("changed");
store = v;
}
},
};
})();
obj.value = 10;//changed
obj.value = 10;
Related Topics
Explain the Encapsulated Anonymous Function Syntax
How to Pass Props to {This.Props.Children}
JavaScript: Client-Side Vs. Server-Side Validation
How to Check If a String "Startswith" Another String
How to Convert Decimal to Hexadecimal in JavaScript
How to Add 1 Day to Current Date
How to Convert an Image into Base64 String Using JavaScript
Trigger a Button Click With JavaScript on the Enter Key in a Text Box
How to Check If Two Arrays Are Equal With JavaScript
JavaScript: Do I Need to Put This.Var For Every Variable in an Object
How to Get the Caret Column (Not Pixels) Position in a Textarea, in Characters, from the Start
"Uncaught Syntaxerror: Cannot Use Import Statement Outside a Module" When Importing Ecmascript 6
How to Send an Email from JavaScript
Jquery Event Keypress: Which Key Was Pressed
Recursive Function Returns Undefined
Uncaught Referenceerror: $ Is Not Defined
How to Make Setinterval Also Work When a Tab Is Inactive in Chrome