richellyitalo
9/27/2018 - 3:37 AM

Post (Create) com Redux

O necessário para realizar um post e tratar seus erros

// src/reducers/errorsReducer.js
import { GET_ERRORS } from '../actions/types'

const initialState = {}

export default (state = initialState, action) => {
  switch (action.type) {
    case GET_ERRORS:
      return action.payload
    default:
      return state
  }
}
// src/actions/profileActions.js
// importações
// Importando ação que realizará o envio
import axios from 'axios'

// Types
import { GET_ERRORS } from './types';

export const createProfile = (profileData, history) => dispatch => {
  axios
    .post('/api/profile', profileData)
    .then(res => history.push('/dashboard'))
    .catch(err => dispatch({
      type: GET_ERRORS, // Define os erros
      payload: err.response.data
    }))
}
// src/Components/create-profile/CreateProfile.js
// importações
// Importando ação que realizará o envio
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { createProfile } from '../actions/profileActions'

class CreateProfile extends Component {
  
  // Estado
  state = {
    name: '',
    errors: {}, // ver componentWillReceiveProps
    // ...
  }
  
  // Envio do form
  onSubmit = e => {
    e.preventDefault()

    const profileData = {
      name: this.state,
      // ...
    }
    
    // Envia os dado com o history para realizar o redirecionamento
    this.props.createProfile(profileData, this.props.history)
  }

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value })
  }

  // Recebimento dos erros e definindo no state
  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors })
    }
  }
  
  render () {
    return (
      <form onSubmit={this.onSubmit}>
        <input 
          type="text" 
          name="name" 
          value={this.value} 
          onChange={this.onChange} 
        />
        <button>Enviar</button>
      </form>
    )
  }
}

CreateProfile.propTypes = {
  errors: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
  errors: state.errors
})

export default connect(
  mapStateToProps,
  { createProfile }
)(withRouter(CreateProfile))