首页 > 解决方案 > React Native async await dispatch store

问题描述

So I want to make a login feature, in here server will validate first if the username or password is correct or not. I'm using store, react - redux.

Here is my code when login button pressed

const [statusLogin,setStatusLogin] = useState(null)
let loginInfo = []

function loginButton(){
    (async () => {
            loginInfo = {username:username,password:password}
            const { status } = await dispatch(getUser(loginInfo))
            if (status==1){
                console.log(status,'in status if 1')
                setStatusLogin('granted')
            }else{
                console.log(status,'in status if else')
                setStatusLogin(null)
            }
    })();
}

Here is my store that suppose to return value 1 or else if it returned value 1 geb statusLogin will changed as granted

export function getUser(body){
    return dispatch =>{
        if (!body){
            setTimeout(() => {
                console.log('no username/pass')
            }, 2000);
        }else{
            setTimeout(() => {
                console.log('username/pass validated returning with value 1')
            }, 2000);
        }
    }
}

help me please

标签: react-nativeasynchronousasync-awaitreact-reduxreact-hooks

解决方案


这可能会有所帮助

...
function loginButton() {
  (async () => {
    loginInfo = { username: username, password: password };
    await dispatch(getUser(loginInfo, callback));
  })();
}

function callback = (status) => {
  if (status == 1) {
    console.log(status, "in status if 1");
    setStatusLogin("granted");
  } else {
    console.log(status, "in status if else");
    setStatusLogin(null);
  }
};

减速器.js

export function getUser(body, callback){
    return dispatch =>{
        if (!body){
            setTimeout(() => {
                console.log('no username/pass');
                callback(0);
            }, 2000);
        }else{
            setTimeout(() => {
                console.log('username/pass validated returning with value 1')
                callback(1);
            }, 2000);
        }
    }
}

推荐阅读