Problem with routing in ReactJs and Redux

23 Views Asked by At

App.js

function App() {
  const { auth } = useSelector(store => store);
  const dispatch = useDispatch();
  const jwt = localStorage.getItem("jwt");

  useEffect(() => {
    dispatch(getProfileAction(jwt));
  }, [jwt]);

  return (
    <div className="">
      <Routes>
        <Route path="/*" element={auth.user ? <HomePage /> : <Authentication /> } />
        <Route path="/message" element={<Message />} />
        <Route path="/*" element={<Authentication />} />
      </Routes>
    </div>
  );
}

export default App;

auth.action.js

export const getProfileAction = (jwt) => async (dispatch) => {
  dispatch({ type: GET_PROFILE_REQUEST }); // Dispatch REGISTER_REQUEST action before the API call
  try {
    const { data } = await axios.get(
      `http://localhost:8080/api/users/profile`,
      {
        headers: {
          Authorization: `Bearer ${jwt}`,
        },
      });
    
    console.log("profile------", data);
    dispatch({ type: GET_PROFILE_SUCCESS, payload: data.user }); // Dispatch REGISTER_SUCCESS with data in payload
  } catch (error) {
    console.log("--------", error);
    dispatch({ type: GET_PROFILE_FAILURE, payload: error }); // Dispatch REGISTER_FAILURE with error message
  }
};

auth.reducer.js

import { GET_PROFILE_FAILURE, GET_PROFILE_REQUEST, GET_PROFILE_SUCCESS, LOGIN_FAILURE, LOGIN_REQUEST, LOGIN_SUCCESS, REGISTER_FAILURE, REGISTER_REQUEST, REGISTER_SUCCESS} from "./authenticationType";

const initialState={
    jwt:null,
    error:null,
    loading:false,
    user:null
}
export const authReducer=(state=initialState, action)=>{
    switch (action.type) {
        case LOGIN_REQUEST:
        case REGISTER_REQUEST:
        case GET_PROFILE_REQUEST:
            return {...state, loading:true, error:null}

        case GET_PROFILE_SUCCESS:
            return {...state, user:action.payload, error:null, loading:false}

        case LOGIN_SUCCESS:
        case REGISTER_SUCCESS:
            return {...state, jwt:action.payload, loading:false, error:null}

        case LOGIN_FAILURE:
        case REGISTER_FAILURE:
        case GET_PROFILE_FAILURE:
            return {...state, loading:false, error:action.payload}

        default:
            return state;
    }
}

When I log in, I am not redirected to HomePage. Although authorization was successful. In result I can't go to HomePage.

Console:

login {token: 'eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDb2Rld2l0aHZsYWQiL…9tIn0.2dobkC1zmyyge15lDPZhYE3ZVbNJ35KQG5cvehSrOgc', message: 'Login Success'}message: "Login Success"token: "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDb2Rld2l0aHZsYWQiLCJpYXQiOjE3MTEzMDI1NDEsImV4cCI6MTcxMTM4ODk0MSwiZW1haWwiOiIzMzNAZ21haWwuY29tIn0.2dobkC1zmyyge15lDPZhYE3ZVbNJ35KQG5cvehSrOgc"[[Prototype]]: Object auth.action.js:66 profile------

After log in, I need to redirect to the HomePage

0

There are 0 best solutions below