Reputation: 331
I would like to know how to render a component after it has finished changing a hook.
For example what I have done in the following component using useEffect.But with the drawback that when I want to use the component I get:
‘HomeClienteOProveedor’ cannot be used as a JSX component. Its return type ‘void’ is not a valid JSX element.
const HomeClienteOProveedor = () => {
const [cliente, setCliente] = useState(true)
getItem("clientType").then(res => {
if (res=="1"){
setCliente(true)
}else{
setCliente(false)
}
})
useEffect(() => {
if (cliente){
return ( ()=>{
<HomeCliente />
});
}else{
return ( ()=>{
<HomeProveedor />
});
}
}, [ cliente]);
}
Why can I use something like this:
setCliente((true) => {
console.log("its true!");
});
Upvotes: 0
Views: 53
Reputation: 16576
The more idiomatic way to do what you're doing is to run the async code in the effect and then condition the render off the stateful value:
const HomeClienteOProveedor = () => {
const [cliente, setCliente] = useState(true)
useEffect(() => {
getItem("clientType").then(res => {
if (res == "1") {
setCliente(true);
} else {
setCliente(false);
}
})
}, []);
return cliente ? <HomeCliente /> : <HomeProveedor />
}
Upvotes: 4