Reputation: 341
The drawback I have is that, after usingEffect, the values of rubro1 and rubro2 are not changed. That is, changes in useEffect of rubro1 and rubro2 are only affected in useEffect.
Is there a way to change rubro1 and rubro2 in useEffect and then see that change throughout the element? Or do I just have to use hooks ?
let rubro1=""
let rubro2=""
const[ thereIsRubros, setThereIsRubros]=useState(false)
useEffect(() => {
getItem("rubro1").then(res => {
if(res!=null || res!= undefined){
rubro1=res
setThereIsRubros(true)
getItem("rubro2").then(res => {
if(res!=null || res!= undefined){
rubro2=res
}
})
}
})
}, []);
if (tehreIsRubros){
if(rubro1!=""&&rubro2==""){
return (//Return some HTML code)
}
}
Upvotes: 0
Views: 125
Reputation: 672
try to remove variable and work only with costants
note that I'm using only one useState so you'll be able to update both rubro1 & rubro2 with one instruction and avoid multiple re-renderings
const [thereIsRubros, setThereIsRubros] = useState({rubro1: undefined, rubro2: undefined})
useEffect(() => {
getItem("rubro1").then(res => {
if(res){
setThereIsRubros({...thereIsRubros, rubro1:res})
getItem("rubro2").then(res => {
if(res){
setThereIsRubros({...thereIsRubros, rubro2:res})
}
})
}
})
}, []);
if (tehreIsRubros.rubro1 && tehreIsRubros.rubro2){
return (//Return some HTML code)
}
moreover remove if(res!=null || res!= undefined)
just do if(res)
, it will check if(res!=null && res!= undefined)
that I guess is your goal
Upvotes: 1
Reputation: 574
If you want to update your component every time you set a new value, you have to use useState
, if you don't want to update your component every time you set a new value but you want to keep a value between re-renderings, then use useRef
.
If you do what you're doing right now, rubro1
and rubro2
are gonna be re-initialized to empty string with every re-render of the component.
Side note, you can use async/await
to improve the legibility of your code.
The following code correctly sets the right values for the variables after every update:
const [rubro1, setRubro1] = useState("");
const [rubro2, setRubro2] = useState("");
const [thereIsRubros, setThereIsRubros] = useState(false);
useEffect(() => {
getItem("rubro1").then((res) => {
if (res != null || res != undefined) {
setRubro1(res);
setThereIsRubros(true);
getItem("rubro2").then((res) => {
if (res != null || res != undefined) {
setRubro2(res);
}
});
}
});
}, []);
if (thereIsRubros) {
if (rubro1 != "" && rubro2 == "") {
return; // do stuff
}
}
Upvotes: 1