Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/erabossid/react-usereducer


https://github.com/erabossid/react-usereducer

Last synced: about 1 month ago
JSON representation

Awesome Lists containing this project

README

        

# React Hooks - useReducer

## counter app code
```
import React, {useReducer} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../App.css';

const PLUS ="PLUS";
const MINUS = "MINUS";

function reducer(state, action){
switch(action.operator){
case PLUS:
return state + 1;
case MINUS:
return state<=0?0:state-1;
default:
return state;
}
}

export default function Counter (){
const [count, dispatch] = useReducer(reducer, 0);

function increment(){
return dispatch({operator:PLUS});
}
function decrement(){
return dispatch({operator:MINUS})
}
return(



{count}



Decrease by 1
Increase by 1



);
}
```

## Login code
```
import React, { useReducer } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../App.css';
import userAccess from './users.component';

function loginReducer(state, action) {
switch (action.type) {
case 'field': {return {
...state, [action.fieldName]: action.value,
};
}
case 'login': {return {
...state, isLoading: true, isLoggedIn:false, error:""
};
}
case 'success': {return {
...state, isLoading: false, isLoggedIn:true, error:""
};
}
case 'error': { return {
...state, isLoggedIn: false, isLoading: false, error: 'Invalid username or password!',
username: "", password: ""
};
}
case 'logout': { return {
...state, username:"", password:"", isLoading:false, isLoggedIn: false, error:""
};
}
default:
return state;
}
}

const initialState = {username: "", password: "", error:"", isLoading: false, isLoggedIn: false };

export default function LoginUseReducer() {
const [state, dispatch] = useReducer(loginReducer, initialState);
const { username, password, error, isLoading, isLoggedIn } = state;

function onChangeUsername(e){
dispatch({type: 'field', fieldName: 'username', value: e.target.value})
};

function onChangePassword(e){
dispatch({type: 'field', fieldName: 'password', value: e.target.value})
};
function onClickLogout(e){
dispatch({type:'logout'})
};

const onSubmitLoginInfo = async (e) => {
e.preventDefault();

dispatch({ type: 'login' });

try {
await userAccess({ username, password });
dispatch({ type: 'success' });
} catch (error) {
dispatch({ type: 'error' });
}
};

return (



{isLoggedIn ? (

Welcome {username}!


Logout
) : (


Login


{error &&

{error}

}





{isLoading ? "Logging in..." : "Login"}




)}


);
}
```