Render component in jsx based on async function returning boolean

烂漫一生 提交于 2021-02-11 15:40:44

问题


I'm trying to render an html element to render based on the return value of an async/await function. I can't seem to get it working correctly.

Below is the async function being called

const isAuthorized= async() => {
  const isAuthorized = await Promise.resolve().then(() => false);
  console.log("isAuthorized =", isAuthorized);
  return isAuthorized;
}

Below is the jsx:

const ComponentName= () => {
    return (
        <div>
            {Promise.resolve(isAuthorized()).then(res => {res ? <p>User is authorized</p> : <p>User is not authorized</p>})}
        </div>
    )
}

export default ComponentName;

This is the error I'm getting:


回答1:


You need to keep a state in your component to track whether your user is authorized or not. Then you can use a useEffect hook to check the status. Your component should render (and re-render) based on the state change.

https://codesandbox.io/s/promiseinuseeffect-do22b?file=/src/App.js




回答2:


It is imposible in React.

1) Try use async/await

2) Make you preparation data in useEffect ( componendDidUpdate )

const ComponentName = () => {
    const [isAuth, setIsAuth] = setState(undefined);
    React.useEffect(() => {
        (async function() {
            if (!isAuth) {
                const result = await isAuthorized();
                setIsAuth(result);
            }
        })();
    }, []);
    const text = isAuth ? 'User is authorized' : 'User is not authorized';
    return (
        <div>
            <p>{text}</p>
        </div>
    );
};




回答3:


I was able to get it working using state

class ComponentName extends Component {
    constructor(props) {
        super(props);
        this.state= {
            isAuthorized: false
        }
    }

    async componentDidMount(){
        const isAuthorized = await Promise.resolve().then(() => false);
        this.setState({isAuthorized: isAuthorized});
    }

    render() {
        return (
            <div>
                {this.state.isAuthorized ? <p>User is authorized</p> : <p>User is not authorized</p>}
            </div>
        )
    }
}

However, I don't think it's secure having a variable like this as state on the dom?



来源:https://stackoverflow.com/questions/61388307/render-component-in-jsx-based-on-async-function-returning-boolean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!