JAOdev
JAOdev

Reputation: 331

Render a component after a hook is correctly changed

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

Answers (1)

Nick
Nick

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

Related Questions