0

I am building a django react-redux based application. I am using Django rest framework's token authentication for authentication and using react-redux. My login is working perfect, after a user log's in his token is saved in the local storage. So if a user reloads his page or comes again, he doesn't need to login again. My login is working perfectly. But the saved auth token check method is not working. As per code after AUTH_TOKEN_CHECK_START, it should dispatch AUTH_TOKEN_CHECK_SUCCESS or AUTH_TOKEN_CHECK_FAIL but nothing is happening

Check the below image, to understand more Actions.js


export const authTokenCheckStart = () => {
    return {
        type: actionTypes.AUTH_TOKEN_CHECK_START,
        payload: {
            loading: true,
            isAuthenticated: false,
            token: null,
        }
    }
};

export const authFail = (type:string) => {
    return {
        type: type,
        payload: {
            loading: false,
            isAuthenticated: false,
            token: null,
            user: null,
            error: null
        }
    }
};

export const authTokenCheck = (token:string) => (dispatch:any) => {
    dispatch(authTokenCheckStart());
    Axios.get(authSignupAPI, {
        headers:{
            Authorization: `Token ${token}`
        }
    }).then((res)=>{
        console.log(actionTypes.AUTH_LOGIN_SUCCESS);
        dispatch({
            type:actionTypes.AUTH_TOKEN_CHECK_SUCCESS,
            payload:{
                token: token,
                loading: false,
                isAuthenticated:true,
                user:res.data,
                error: null,
            }
        })
    }).catch((error)=>{
        localStorage.removeItem('Token');
        dispatch(authFail(actionTypes.AUTH_TOKEN_CHECK_FAIL))
    })
};

Reducer.js


const authReducer = (state=initialState, action:any) =>{
    switch (action.type) {
        case actionTypes.AUTH_LOGIN_START:
            return {
                ...state,
                loading: action.payload.loading,
                isAuthenticated: action.payload.isAuthenticated,
                token: action.payload.token,
                error: action.payload.error,
            };


        case actionTypes.AUTH_LOGIN_SUCCESS:
            return {
                ...state,
                loading: action.payload.loading,
                isAuthenticated: action.payload.isAuthenticated,
                token: action.payload.token,
                error: action.payload.error,
                user: action.payload.user
            };

        case actionTypes.AUTH_LOGIN_FAIL:
            return {
                ...state,
                loading: action.payload.loading,
                isAuthenticated: action.payload.isAuthenticated,
                token: action.payload.token,
                error: action.payload.error,
                user: action.payload.user
            };

        case actionTypes.AUTH_TOKEN_CHECK_START:
            return {
                ...state,
                loading: action.payload.loading,
                isAuthenticated: action.payload.isAuthenticated,
                token: action.payload.token,
                error: action.payload.error,
                user: action.payload.user
            };

        case actionTypes.AUTH_TOKEN_CHECK_SUCCESS:
            return {
                ...state,
                loading: action.payload.loading,
                isAuthenticated: action.payload.isAuthenticated,
                token: action.payload.token,
                error: action.payload.error,
                user: action.payload.user
            };
        case actionTypes.AUTH_TOKEN_CHECK_FAIL:
            return {
                ...state,
                loading: false,
                isAuthenticated: action.payload.isAuthenticated,
                token: action.payload.token,
                error: action.payload.error,
                user: action.payload.user
            };
        case actionTypes.AUTH_LOGOUT:{
            return initialState
        }
        default:
            return state

    }
};

Login Component


const Login =(props:any) =>{
    const [state, setState] = useState({
        Email:'',
        Password:''
    });


    const inputOnChange = (e:any) => {
        setState({
            ...state,
            [e.target.name]: e.target.value
        })
    };

    useEffect(()=>{
        const token = localStorage.getItem('Token');
            if(token !== null) {
                props.authTokenCheck()
            }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[localStorage.getItem('Token')]) ;


    const loginButtonEvent = (e:any) => {
        props.authLogin(state.Email, state.Password)
    };

return(
  <div>
     {props.auth.isAuthenticated?
      <div>
       <h1>I am authenticated</h1>
       <h2>{`${props.auth.isAuthenticated}`}</h2>
      </div>:
         <div>
            <div>
               {props.auth.loading?
                   <div><h1>Loading</h1></div>
                    :
          <div>
               <input placeholder={'Email Address'} 
                      name={'Email'} onChange={(e)=>{inputOnChange(e)}} 
                      type="text"/>
              <input placeholder={'Password'} 
                      name={'Password'} 
                      onChange={(e)=>{inputOnChange(e)}} 
                         type="password"/>
              <button onClick={(e)=>{loginButtonEvent(e)}}>Login</button>
          </div>
          }
       </div>
     </div>}
  </div>



};

const mapStateToProps = (state:any) =>({
    auth: state.auth
});
const mapDispatchToProps = (dispatch:any) => {
    return {
        // dispatching actions returned by action creators
        authLogin: (email:string,password:string) => dispatch(authLogin(email,password)),
        authTokenCheck: () => dispatch(authTokenCheck()),

    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Login)

Error Image

1 Answer 1

1

You could've written this code better but I don't see a problem why it wouldn't work.

  1. I noticed you are passing authSignupAPI instead of the login url so maybe that's the problem?
  2. Have you checked that a Http request was actually sent out to your api? you can go to the Network tab in chrome dev tools to check this.
  3. Have you checked for an error in your console?
  4. Try putting debugger; statement in the action and inside each of the callbacks and this might help you find the problem.
Sign up to request clarification or add additional context in comments.

2 Comments

The signup api is just name of the constant, it is actually the api endpoint for getting the user information using token. The problem is with the dispatch/javascript. Javascript is not sending the http request and it is also not dispatching the related action.
I would start by putting a debugger statement or a breakpoint inside authTokenCheck and inside each of the promise callbacks. Check that dispatch is defined (It should be if you configured redux-thunk correctly), check that the url is defined and that Axios.get is defined. In addition check the console for any errors and the network tab to see if a request is actually dispatched. Maybe try using the regular fetch api instead of axios. If you could post a code sandbox example it would be easier to help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.