How to request and update a status before render

Asked

Viewed 199 times

-1

I’m making an application and was creating a Privaterouter.

Since I am using a Fake API (hai-server) it generates me a token on login and I can block calls from some routes if I do not pass this token, there is no verifyToken, then I had the idea of validating the Privaterouter through a call in one of these Urls and giving me success I changed a variable or state to validate the component as in the image.

Only, React because it is asynchronous it renders the Return before returning the call, I tried it with useEffect and useEffect but without success.

Someone would have an idea, I know there are other methods but this was what I imagined for the type of Api I’m using to have more security after they login..

inserir a descrição da imagem aqui

2 answers

0

Can use conditional rendering...

export default class App extends Component {

     state = { requisicao: null }

     funcaoDeRequisicao = async () => {
          //aqui faz a requisicao e seta o estado
     }

     return requisicao && <Text>TESTE</Text>

}

What will occur is that the text after the operation '&&' will only be rendered if the requisical state is different from null, Undefined or false.

0

Usually to avoid rendering before a request is returned I use if before Return, returning anything I want, for example:

export default class App extends Component {
  state = { retorno: false }

  async function req(){
     //requisicao feita aqui com retorno
     //.then seta retorno = true
  }
  render() {
    if(!this.state.retorno){
       //se o retorno for false ele retorna qualquer coisa que você queira
       return({/* qualquer coisa aqui */});
    }
    //se for true ele vai retornar o render normal
    return();
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.