Clement Levesque
Clement Levesque

Reputation: 1212

Initialize form values with redux form initialize function and a GET request

I am trying to initiliaze my form with values coming from my server via an HTTP get request.

My component has a userId has a props (for testing I just hardcoded the id in the request with 1) and I would like to retrieve all the corresponding values from the database and initialize my fields with them.

I use redux form and I found (here) that it is possible to use the initialize redux form function to get it done. Actually it works when I hardcode the values in my initData object but does not work when retrieving data from the http request as it seems to do the get after creating the initData object..

I don't know if I am clear but in my console it shows me this :

"USER => Object {}" Uncaught TypeError: Cannot read property 'toString' of undefined Object {ID: 1, FIRSTNAME: "Roger" etc...} Roger

That means that the get function works, but it is available after the initData object initialization....

Here is an extract of my code :

class LoginForm extends React.Component {

  handleInitialize () {
    const user = {};
    // TODO: Gérer le cas où il n'y a pas de userId
    fetch('http://localhost:3000/user/1')// + this.props.userId)
      .then((resp) => resp.json())
      .then((data) => {
        console.log(data);
        console.log(data.FIRSTNAME);
        user.FIRSTNAME = data.FIRSTNAME;
        user.LASTNAME = data.LASTNAME;
        user.EMAIL = data.EMAIL;
        user.CITY = data.CITY;
        user.RANKING = data.RANKING;
        user.AVATAR = data.AVATAR;
      })
      .catch((error) => {
        console.log(error);
      });
    console.log('USER => ', user);

    if(user) {
      const initData = {
        'firstname': user.FIRSTNAME.toString(),
        'lastname': user.LASTNAME.toString(),
        'city': user.CITY.toString(),
        'email': user.EMAIL.toString(),
        'ranking': user.RANKING.toString(),
        'avatar': user.AVATAR.toString()
      };
      console.log(initData);
      this.props.initialize(initData);
    }
  }

  componentDidMount () {
    this.handleInitialize();
  } 

Any idea?

Thanks a lot for your help and sorry if my question seems obvious, I am a beginner :)

Upvotes: 2

Views: 2901

Answers (1)

jpdelatorre
jpdelatorre

Reputation: 3593

Try moving your this.props.initialize inside the then(data =>{...}) block. If that didn't fix it, make sure you have enableReinitialize set to true.

reduxForm({
  form: 'formName',
  ...
  enableReinitialize: true,
})(LoginForm);

Upvotes: 3

Related Questions