Search code examples
javascriptreactjsreduxmaterial-uiredux-form

"toggled" attribute not working (redux-form-material-ui)


I'm trying to use Toggle from redux-form-material-ui:

import { Toggle } from 'redux-form-material-ui'

It works ok updating the toggled value to the store on its onChange:

<Col xs='3'>
    <h3 className="title-page">Parceiro</h3>
    <Field name="possui-parceiro" component={Toggle} label="Possui parceiro?" />
</Col>

Problem is: I make a call to some API and I need to update the value of this toggled "programatically". Theoretically, I can use the toggled attribute as stated here, but this just doesn't work:

<Col xs='3'>
    <h3 className="title-page">Parceiro</h3>
    <Field name="possui-parceiro" component={Toggle} toggled={this.state.someBloodyState} label="Possui parceiro?" />
</Col>

Which leads me to believe that in this case redux-form is just on the way of the update / manipulation process, forcing me to somehow update the form on the store to toggle the value, and it looks messy to dispatch such action. Anyway, how do you proceed in such cases?


Solution

  • I would store the API result in the redux state, read it from your mapStateToProps and pass it to the component in the property initialValues setting enableReinitialize: true.

    These 2 properties are the way of redux-form to change stuff programmatically "later on" after the form already rendered.

    Otherwise , if you can fetch your data before even rendering the form, you can just use initialValues without enableReinitialize.

    Another way is to use the change function provided by redux form

    More info in the docs