-
Notifications
You must be signed in to change notification settings - Fork 0
2. Create AddEmployee
Fabian Larrañaga edited this page Dec 1, 2017
·
18 revisions
import React from 'react'
let AddEmployee = () => {
let input
return (
<div className='add-employee-form'>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
input.value = ''
}}>
<h1>Please add your name</h1>
<div className='question'>
<input type='text' ref={ node => { input = node } } required/>
<label>Name</label>
</div>
<button type='submit'>
Add Employee
</button>
</form>
</div>
)
}
export default AddEmployee
...
import AddEmployee from './components/AddEmployee';
class App extends Component {
render() {
return (
<div className='App'>
<header className='App-header'>
<img src={logo} className='App-logo' alt='logo' />
<h1 className='App-title'>Welcome to Pony o Castor!</h1>
</header>
<AddEmployee />
</div>
);
}
}
export const addEmployee = (name) => ({
type: 'ADD_EMPLOYEE',
name
})
const addEmployee = (state = [], action) => {
switch (action.type) {
case 'ADD_EMPLOYEE':
return [
...state,
{
name: action.name,
pony: true
}
];
default:
return state;
}
}
export default addEmployee
// src/index.js
...
import reducer from './reducers'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Edit src/components/AddEmployee.js
to dispatch the action addEmployee
...
//imports
import { connect } from 'react-redux' // <---- (* Add this *)
import { addEmployee } from '../actions' // <---- (* Add this *)
let AddEmployee = ({ dispatch }) => { // <---- (* Add this *)
...
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addEmployee(input.value)) // <---- (* Add this *)
input.value = ''
}}>
...
export default connect()(AddEmployee) // <---- (* Add this *)
Let's check if the input works :)
Edit the reducer to console.log the AddEmployee action.
...
const addEmployee = (state = [], action) => {
switch (action.type) {
case 'ADD_EMPLOYEE':
let newState = [
...state,
{
name: action.name
}
]
console.log(newState);
return newState;
default:
console.log(state);
return state;
}
}
export default addEmployee