Skip to content

Instantly share code, notes, and snippets.

@paulobunga
Last active June 7, 2022 15:43
Show Gist options
  • Save paulobunga/6c97bdfa38fd4d560f74243c09649308 to your computer and use it in GitHub Desktop.
Save paulobunga/6c97bdfa38fd4d560f74243c09649308 to your computer and use it in GitHub Desktop.
Redux example complete
const { useDispatch, useSelector } = require("react-redux");
// INITIAL STATE
const initital = {
  authenticated: false,
  token: "",
  error: "",
};
// Types
const AUTH_SUCCESS = "AUTH_SUCCESS";
const AUTH_ERROR = "AUTH_ERROR";
// Actions
const login =
  ({ username, password }) =>
  (dispatch) => {
    APIService.login(username, password)
      .then((data) => {
        dispatch({ type: AUTH_SUCCESS, payload: data.token });
      })
      .catch((error) => {
        dispatch({ type: AUTH_ERROR, payload: "Invalid password" });
      });
  };
// Reducer
const reducer = (state = initital, action) => {
  switch (action.type) {
    case AUTH_SUCCESS:
      return {
        ...state,
        authenticated: true,
        token: action.payload,
      };

    case AUTH_ERROR:
      return {
        ...state,
        authenticated: false,
        error: action.payload,
      };
    default:
      return { ...state };
  }
};
const store = createStore(reducer, applyMiddleware(ReduxThunk));
const LoginScreen = () => {

  const dispatch = useDispatch();
  const state = useSelector(state => state);

  const submit = () => {
    dispatch(login({ username, password }));
  }

  useEffect(() => {
    if(state.authenticated) {
      redirectHome()
    }
  }, [state]);

  return (
    <Provider store={store}>
      {state.error ?? <message>{state.error}</message>}
      <input username />
      <input password />
      <button onpress="submit()">LOGIN</button>
    </Provider>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment