Sometimes function has built-in callback
function, "This function is called when something happens"
In my case, I want to make callback function which is called after a certain static value is changed
For example,
class MyVariable(){
static myVal = 1;
}
const FileUploader = (props) =>{
myAlert(){
console.log("val is changed!");
}
changeValue2(){
MyVariable.myVal = 2;
myAlert();
}
changeValue3(){
MyVariable.myVal = 3;
myAlert();
}
changeValue4(){
MyVariable.myVal = 4;
myAlert();
}
}
I want to call myAlert()
after myVal
is changed.
so currently I write myAlert()
third times.
I wonder is it possible to do this automatically like making the callback which is called when myVal is changed
Is there any way for this idea? I am using React
3
Answers
Since you are using a class you can include this method:
and you update
myVal
with the method instead.you can also make
myVal
a stateconst[myVal,setMyVal] = useState(1)
and usesetMyVal()
to update it then add thisuseEffect
:it will run each time
myVal
is updated.You could define a setter and use a private field to store the value.
You can change
myVal
to a setter and also allow registering of listeners or subscribers. Then, when the value is changed, call the listeners from within the setter.