Home > OS >  How can I store my JWT token in userInfo?
How can I store my JWT token in userInfo?

Time:12-02

I try a lot of things but I can´t go on .. I stucked ... If I login in to my account it works I get also my userInfo but only userID and my password.. but I would have my token also ..

I wrote an if state where I catch my token but I want to set it also in the localStorage and I don´t know how to do it..

export const login = (userID, password) => async (dispatch) => {
    try {
        dispatch({ type: USER_LOGIN_REQUEST });
       
        const url = "http://localhost:8080/authenticate/";
        const config = {
          auth: {
            username: userID,
            password,
          },
        };
    
        const data = {};
        const response = await axios.post(
            url, 
            data, 
            config,
        )

        dispatch({ type: USER_LOGIN_SUCCESS, payload: config});
        //localStorage.setItem("userInfo", JSON.stringify(config) );
 
        if (response.status === 200) {
          // Login succeeded
          const token = response.data.token;
          console.log("TOKEN\n"   token);
          localStorage.setItem("userInfo", JSON.stringify(config) );
        }
      } catch (error) {
        //alert("Sorry, login failed");
        dispatch({
            type: USER_LOGIN_FAIL,
            payload:
                error.response && error.response.data.ErrorMessage
                    ? error.response.data.ErrorMessage
                    : error.message,
        });
      }
};

CodePudding user response:

try this

export const login = (userID, password) => async (dispatch) => {
    try {
        dispatch({ type: USER_LOGIN_REQUEST });
       
        const url = "http://localhost:8080/authenticate/";
        const config = {
          auth: {
            username: userID,
            password, //this should not be saved in your local storage delete this from here
          },
        };
    
        const data = {};
        const response = await axios.post(
            url, 
            data, 
            config,
        )

        dispatch({ type: USER_LOGIN_SUCCESS, payload: config});
 
        if (response.status === 200) {
          // Login succeeded
          config.token = response.data.token;
          
        }
        localStorage.setItem("userInfo", JSON.stringify(config) );
      } catch (error) {
        //alert("Sorry, login failed");
        dispatch({
            type: USER_LOGIN_FAIL,
            payload:
                error.response && error.response.data.ErrorMessage
                    ? error.response.data.ErrorMessage
                    : error.message,
        });
      }
};
  • Related