0

I want to fetch data every time a route is visited

I tried to return something in my async function but i got a promise and i need just the value for rendering

This is my fetch function i want to execute everytime a route is visited

   isLogged = async()=>{
    //return 0;
    let response = await 
            fetch(`${CONFIG.server}/getStudentLogin`,{
        method: 'GET',
        headers: {
            'Authorization': 
                             store.getState().userDataLogged.token,
            'Content-Type': 'application/json'
        }
    })
    let dataResponse = await response.json();
    console.log(dataResponse)
    if(dataResponse.status == 500){
        //console.log("xd")
        return false;
    }
    return true;
}

And this is my render function for example

  <Route exact path="/student" render={()=>(
      this.isLogged() ? (
        this.isStudent() ? (                         
          <StudentView/>
        ):(
          <TeacherView/>
        )
      ):(
        <Redirect to="/login"/>
      )
   )}/>

The problem is isLogged function return me a promise but i need to return just a value, for example true or false

1 Answer 1

1

In case you need to execute the promise you could simply add async before the function definition in render and then use await before the this.isLogged()

<Route exact path="/student" render={async ()=>(
      await this.isLogged() ? (
        this.isStudent() ? (                         
          <StudentView/>
        ):(
          <TeacherView/>
        )
      ):(
        <Redirect to="/login"/>
      )
   )}/>
Sign up to request clarification or add additional context in comments.

1 Comment

I got this error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.