Listening For Variable Changes in JavaScript

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:
  1. Add userId in your component state.
  2. Listen for the storage event. See StorageEvent
  3. 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

  1. In getUserId return data.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



Leave a reply



Submit