Skip to content

Instantly share code, notes, and snippets.

@richellyitalo
Last active May 2, 2019 01:01
Show Gist options
  • Save richellyitalo/8adb6be84612de2a942f81357d02eba4 to your computer and use it in GitHub Desktop.
Save richellyitalo/8adb6be84612de2a942f81357d02eba4 to your computer and use it in GitHub Desktop.

store/actions/todos.js

export const addTodo = text => ({ type: 'ADD_TODO', payload: { text } });

store/reducers/todos.js

const INITIAL_STATE = [
  { id: 1, text: 'Estudar pra caralho' },
  { id: 2, text: 'Estudar mais ainda' },
  { id: 3, text: 'Por em prática!' },
];

export default function todos(state = INITIAL_STATE, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [...state, { id: Math.random(), text: action.payload.text }];
    default:
      return state;
  }
}

store/reducers/index.js

import { combineReducers } from 'redux';
import todos from './todos';

export default combineReducers({ todos });

store/index.js

import { createStore } from 'redux';

import reducers from './reducers';

const store = createStore(reducers);

export default store;

components/TodoList/index.js

import React, { Fragment } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';

import * as TodoActions from '../../store/actions/todos';

const TodoList = ({ todos, addTodo }) => (
  <Fragment>
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
    <button type="button" onClick={() => addTodo('Voltar e fazer novamente!')}>
      Adicionar Todo
    </button>
  </Fragment>
);

TodoList.propTypes = {
  addTodo: PropTypes.func.isRequired,
  todos: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.number,
      text: PropTypes.string,
    }),
  ).isRequired,
};

const mapDispatchToProps = dispatch => bindActionCreators(TodoActions, dispatch);

const mapStateToProps = ({ todos }) => ({ todos });

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(TodoList);

App.js

import React from 'react';
import { Provider } from 'react-redux';

import TodoList from './components/TodoList';
import store from './store';

const App = () => (
  <Provider store={store}>
    <TodoList />
  </Provider>
);

export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment