import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers } from 'redux'
// reducer
const todo = (state,action) =>{
switch(action.type){
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
};
default:
return state;
}
}
const todos = (state=[], action) =>{
switch(action.type){
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
];
default:
return state;
}
};
const todoApp = combineReducers({
todos,
});
const store = createStore(todoApp)
let nextTodoId = 0
class TodoApp extends React.Component{
render (){
return(
<div>
<input ref={node => {this.input = node}} />
<button onClick={()=>{
store.dispatch({
type: 'ADD_TODO',
text: this.input.value,
id: nextTodoId++
});
this.input.value= '';
}} >
ADD TODO
</button>
<ul>
{this.props.todos.map(todo =>
<li key={todo.id}>
{todo.text}
</li>
)}
</ul>
</div>
)
};
}
const render = () => {
ReactDOM.render(
<TodoApp
todos = {store.getState().todos}
/>,
document.getElementById('root')
)
};
store.subscribe(render)
render();