0

This is how my project looks:

class ParentOfForm extends Component{
  constructor(){this.state={initVals: null};}
  componentDidMount(){
    asyncCall.then((values) =>
      setState({
        initVals: {
          initval1: valFromAsync,
          ..
        }
      })
    );
  }
  render(){
    const {initVals} = this.state;
    {!initVals && <Form/>}
    {!!initVals && <Form initialValues={initVals}/>}
  }
}

----------------

class Form extends Component{
  constructor(props){
    super(props);
    this.state = {
      initval1: "",
      ..
    }
  }

  render(){
    return(
      <form..>
        ..
      </form>
    );
  }
}

Form = reduxForm({
  form: "Form",
  validate,
  enableReinitialize: true
})(Form);

export default Form;

So as you can see, I'm trying to use values from an async function as initialValues to initialize the input fields of my form. When I define initialValues inside Form = reduxForm({...}) they get displayed correctly. However when I try to set them dynamically using the async call I can see the values being changed but they all seem to be undefined eventhough I can see them being filled in with console.log(). What am doing wrong?

Obvious alternatives I can't use because reasons: defaultValue, const Form = ().., no parent

MaxV
  • 11
  • 4
  • I am not sure if you meant to show some pseudo code but the part `asyncCall.then(setState(...))` does not seem right. Do you mean `asyncCall.then((values) => setState(...))` ? Also `initVals=null` it should be `initVals: null` – stilllife Sep 13 '18 at 06:43
  • Also you are checking `{!initValues &&
    }` but seems like you meant `initVals` not `initValues` A clean JS code would be better to be able to solve the issue
    – stilllife Sep 13 '18 at 06:49

1 Answers1

0

welcome to SO.

So what is happening is since its an async call the initValues don't show up immediately in the form.Even in the console log it'll show up once the call completes. So there is a time gap between the page loading with a blank form and then the init call completing with the values.

There are 2 ways to handle this :

  1. Show a loading symbol on the form and wait for the async call to complete and fill the init values [UX recommended] see here
  2. Show an empty form with default values till the initValues are fetched, and show them when the call completes. [bad UX practice]
Shivam Gupta
  • 1,198
  • 9
  • 10