简体   繁体   中英

React JSX check if async function return true or false

In a component, I've implemented a function call that has a promised call and returns either true or false . I'm using the call for conditional rendering like below:

return (
  isAuthValid() ? <div>Authenticated</div> : </div>Invalid User</div>
)

isAuthValid has a Rest Call like below:

async function isAuthValid(){
 const response = await getAuth(); 
 // response.data return boolean value (true or false)
 return response.data;
}

I'm receiving Promise {<pending>} from isAuthValid execution instead of boolean value. I can do it with assigning and updating state as well.

eg

const {auth, setAuth} = React.useState(false);

 async function isAuthValid(){
  const response = await getAuth(); 
  setAuth(response.data)
 }

return (
 auth ? <div>Authenticated</div> : </div>Invalid User</div>
)
 

I'm trying to understand why direct execution doesn't work. I've implemented async-await to make it asynchronous. How to make it work like that without using the state hook?

You need to make sure that this code fires when you load your component. You can use the useEffect hook to do this, and pass in an empty array of dependencies so it only runs once.

I switched from async/await into a promise just because they're a little easier for me to get my head around.

import React, {useState, useEffect} from "react";
import getAuth from "./get-auth";

function MyComponent() {
  const [auth, setAuth] = React.useState(false);
  useEffect(() => {
    getAuth()
    .then(response => {
       setAuth(response.data)
    }).catch(error => {
      // If error, let's set their auth to false.
      setAuth(response.data)
    });
  }, []);

  return (
    auth ? Authenticated : Invalid User
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM