How to make useSelector value not null, after doing dispatch?

Viewed 308

I have a problem getting the result from useSelector in const resultLogin and the result is always null, how do I make useSelector updated after going through the dispatch process?

Here is the code I created:

1)Login.js

const dispatch = useDispatch()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [hidePassword, setHidePassword] = useState(true)
const managePasswordVisibility = () => {
    setHidePassword(!hidePassword)
}
const resultLogin = useSelector((state) => state.resultLogin)
const resultError = useSelector((state) => state.error)

const onSubmit = () => {
    dispatch(loginController(username, password));
    if (resultLogin != null) {
        console.log("result success:"+ resultLogin);
    }

    if (resultError != null) {
        console.log("result error:"+ resultError);
    }
}

2)initialState

resultLogin: null,
error: null

3)reducerLogin.js

const newState = { ...state }

switch (action.type) {
      case 'LOGIN_SUCCESS':
            newState.resultLogin = action.valueResultLogin
            break;
      case 'LOGIN_ERROR':
            newState.error = action.value
            break;
}

return newState

4)actionLogin.js

return async dispatch => {        
    try {           
     const result = await axios.post(`${url.https}`, body);
       dispatch(loginSuccess(result.data));
    } catch (error) {
        dispatch(loginError(error));
    }
}

I thank anyone who can help :D

1 Answers

This can be done with useEfeects

useEffect(() => {
    if (resultLogin) {
        console.log("result success:"+ resultLogin);
    }
}, [resultLogin])

useEffect(() => {
    if (resultError) {
        console.log("result error:"+ resultError);
    }
}, [resultError])

const onSubmit = () => dispatch(loginController(username, password));
Related