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>
);
}