Clear field after Submit with Redux and Redux-form

Asked

Viewed 420 times

-2

Talk, guys, after catching a lot and having nowhere else to go, I came to ask for your help.

My scenario is I’m with a form where the fields are the Fields of the Redux-Forms. I need, after Submit, to clear the fields, I have already read the documentation but the code does not work, just passing the Dispatch(reset'nameDoForm')).

I know it may sound ridiculous, but I’m getting beaten to clean the form, on the Reset button, it even works, but not in the action

Someone has already gone through this and/or could give me a help, below my code.

Action:

import axios from 'axios'
import { toastr } from 'react-redux-toastr'
import {reset as resetForm} from 'redux-form';

export const INIT = 'INIT';

const baseURL = 'http://localhost:3333/'

export const create = (values) => {
    axios.post(`${baseURL}usuario`, values)
        .then(resp => {
            toastr.success('Sucesso', 'Operação realizada com sucesso')
            dispatch(resetForm('userForm'))
        })
        .catch(e => {
            e.response.data.forEach(error => {
                toastr.error('Erro', error)
            });
        })
}

Reduce:

import * as UsuarioConstants from '../Actions/UsuarioActions'

const INITIAL_STATE = { nome: 'teste', login: '', senha: '', email: '', list: [] }

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case UsuarioConstants.INIT:
            return { ...state}
        case UsuarioConstants.LIMPAR_CAMPOS:
            return { ...state, nome: '', login: '', senha: '', email: '' }
        default:
            return state
    }
}

Form:

    import React, { Component } from 'react'
    import { reduxForm, Field } from 'redux-form'
    import { bindActionCreators } from 'redux'
    import { create } from '../../main/Actions/UsuarioActions'

    import Nav from '../components/Menu/Nav'
    import Rodape from '../components/Rodape'
    import { connect } from 'react-redux'


    class UsuarioForm extends Component {

        render() {

            const { handleSubmit, pristine, reset, submittinng } = this.props
            const submit = (data, create) => {
                create(data)
            }
            return (
                <div>
                    <Nav />
                    <form role="form" onSubmit={handleSubmit((fields) => submit(fields, create))}>
                        <div className="box-body">
                            <Field name="nome" component="input" />
                            <Field name="login" component="input" />
                            <Field name="senha" component="input" />
                            <Field name="email" component="input" />
                        </div>

                        <div className="box-footer">
                            <button type="submit" className="btn btn-primary">Submit</button>
                            <button type="button" className="btn btn-danger" disable={pristine || submittinng} onClick={reset}>Reset</button>
                        </div>
                    </form>
                    <Rodape />
                </div>
            )

        }
    }

const Form = reduxForm({
    form: 'userForm'
})(UsuarioForm)

const mapStateToProps = state => ({ nome: state.usuario.nome })

const mapDispatchToProps = dispatch => bindActionCreators({
    create
}, dispatch)


export default connect(mapStateToProps, mapDispatchToProps)(Form)

1 answer

-1

Hello, I’ll give you an example of me that I have in an application ready and you adjust the code for you:

Below goes my return:

case LOGOUT_USER:
return {
  ...state
}
case LOGOUT_USER_SUCCESS:
return {
  INITIAL_STATE
}
case LOGOUT_USER_ERROR:
return {
  ...state
}

And down here goes my action:

export const logoutUser = () => {
  return dispatch => {
    dispatch(
      {
        type: LOGOUT_USER
      }
    )
    try {
      logoutUserSuccess(dispatch)
    }
    catch (err) {
      logoutUserError(err, dispatch)
    }
  }
}

const logoutUserSuccess = (dispatch) => {
  dispatch(
    {
      type: LOGOUT_USER_SUCCESS
    }
  )
  AsyncStorage.removeItem('@token_jwt')
  console.log('saiu')
  Actions.loginScreen()
}

const logoutUserError = (err, dispatch) => {
  dispatch(
    {
      type: LOGOUT_USER_ERROR
    }
  )
  Alert.alert('Erro ao sair da conta')
  console.log(err)
}

When passing INITAL_STATE in success, fields are cleared

I don’t use the Redux-form, but the logic is the same, I hope to have helped.

  • i tried to do so too, ams for some reason the form does not have the fields cleared when the state receives the initial value that are the empty fields

Browser other questions tagged

You are not signed in. Login or sign up in order to post.