0

I'm using react-redux hooks to write a login/logout system. Currently i'm facing a problem where inside the logout() & login1() will only run the first dispatch only. Did some research found that redux-thunks might can solve this, but get confused cause redux-thunks are more likely to load data. Anyone have any ideas on it??

import React from "react"
    import {chgStatus,chgName,chgPw} from "../Actions"
    import {useSelector,useDispatch,shallowEqual} from "react-redux";
    import {useHistory} from "react-router-dom";
    import '../App.css'

const LoginOutBtn =()=>{
  const {name,password,status} = useSelector(state=>({
    name: state.name,
    password: state.password,
    status: state.status
  }),shallowEqual);
  const dispatch = useDispatch()
  const history = useHistory()
  const loginStatus = status?
    <span>登出</span> : 
    <span>登入</span>

  const logout=()=>dispatch(
    chgStatus(!status),
    // chgName("logout"),
    //chgPw("123"),
    console.log(status,name,password,456),
    history.push("/subPage1")
  )
  const login=()=>dispatch(
    chgStatus(!status),
    chgName("Qweq"),
    chgPw("pw"),
    console.log(status,name,password,123),
    history.push("/subPage2")
  )

  const login1 =()=>{
    dispatch(
      dispatch(chgStatus(!status)),
      dispatch(chgName("Qweq")),
      dispatch(chgPw("pw")))
    console.log(status,name,password,123)
    history.push("/subPage2")
  }


  const handleClick=()=>{
    if(status){     
      logout()
    }else if(status === false){
      login1()
    }
    console.log(status,name,password,789)

    // logout()
    //   console.log(status,name,password,"logout")
    // login1()
    //   console.log(status,name,password,"login")
  }


  return(
    <>
      <button
        className="btn"
        onClick={handleClick}
      >
        {loginStatus}
      </button>
    </>
  )
}

export default LoginOutBtn
OMG
  • 3
  • 2
  • Can you just have the three individual dispatches? I.E. not wrapped in another dispatch. – Drew Reese Jan 29 '20 at 04:11
  • I recommend you just use react context with hooks. You're over complicating auth with unnecessary library like redux. – SILENT Jan 29 '20 at 04:30
  • it will only run the last dispatch which are chgPw("pw") @DrewReese – OMG Jan 29 '20 at 04:32
  • Also, you are using redux incorrectly. You should have a single action that would dispatch all the details instead of separate ones (ie `chgStatus`, `chgName`, etc) – SILENT Jan 29 '20 at 04:32

1 Answers1

-1

You aren't using redux correctly.

// Actions
function Login(name, password) => ({ type: 'LOGIN', payload: { name, password }});
function Logout() => ({ type: 'LOGOUT' });

// Reducer
function Reducer(state, action) {
...
case 'LOGIN': {
 return { ...state, ...action.payload, status: true };
}
case 'LOGOUT': {
 return { ...state, status: false };
}
...
}

However, I still recommend to not use redux at all. Just use react context with hooks.

SILENT
  • 2,746
  • 1
  • 22
  • 34