2

I have a screen for update previously data "name, email, age, etc". at the first time I call a function that gets data from server name as getProfileData()

after user write the new data I send a POST request for that "update Profile"

and it's a success, but after that, I want to re-render this form with new data, So i call the getProfileData() function to get new data but it's not working to re-render Input Values! it's just still with previous data

I also try with componentDidUpdate() but sadly not re-render :)

So how can i solve it?

Code

getProfileData = async () => {
    let USER_TOKEN =
      '....';
    let AuthStr = `Bearer ${USER_TOKEN}`;
    let response = await API.get('/profile', {
      headers: {Authorization: AuthStr},
    });
    let {
      data: {data},
    } = response;
    let password = '';
    let password_confirmation = '';
    let {name, email, avatar, age, gender, country_id} = data;
    let initialValues = [];
    initialValues.push({
      name,
      password,
      password_confirmation,
      email,
      avatar,
      age,
      gender,
      country_id,
    });
    this.setState({initialValues: initialValues, loading: false}, () =>
      reactotron.log(this.state.initialValues[0]),
    );
  };


  updateProfile = async value => {
    let USER_TOKEN =
      '....';
    let AuthStr = `Bearer ${USER_TOKEN}`;
    const headers = {
      'Content-Type': 'application/json',
      Authorization: AuthStr,
    };
    let response = await API.post('/update_profile', value, {
      headers: headers,
    });
    let {
      data: {data},
    } = response;
    alert(data);
    this.getProfileData(); // called 
  };


 componentDidMount() {
    this.getCountryList();
    this.getProfileData();
  }
  componentDidUpdate(prevProps, prevState) {
    if (prevState.initialValues !== this.state.initialValues) {
      console.log('componentDidUpdate', this.state.initialValues);
      this.setState({initialValues: this.state.initialValues});
    }
  }

UI

<Formik
                  validationSchema={formSchema}
                  initialValues={this.state.initialValues[0]}
                  onSubmit={(values, actions) => {
                    this.updateProfile(values);
                    reactotron.log(values), actions.resetForm();
                  }}>
                  {({
                    handleChange,
                    handleBlur,
                    touched,
                    errors,
                    handleSubmit,
                    values,
                    setFieldValue,
                  }) => (
                    <View>
                      <Item style={styles.item} floatingLabel>
                        <Label style={styles.formLabel}>name</Label>
                        <Input
                          style={styles.value}
                          rounded
                          onChangeText={handleChange('name')}
                          onBlur={handleBlur('name')}
                          value={values.name}
                        />
                      </Item>
                      <Text style={styles.errorText}>
                        {touched.name && errors.name}
                      </Text>
                 </View>
             )}
 </Formik>

1 Answer 1

13

You can use enablereinitialize prop on formik.

<Formik 
  enableReinitialize
  ...
/>

By default it is false, but if its true, what will happen is if you initialValues change, it will rerender. So you can store your initialValues in state.

for example

state = {
  initialValues: { name: '', ...}
}

and when you update the profile data just update that state.

setState({initialValues: newInitialValues })

https://jaredpalmer.com/formik/docs/api/formik#enablereinitialize-boolean

5
  • newInitialValues should be in which function? 😅
    – Oliver D
    Commented Feb 15, 2020 at 19:47
  • when your api gets resolved.Probably in your onSubmit after api has been successful. Commented Feb 15, 2020 at 19:48
  • @OliverD Updated my answer with a resource link and a slight typo for enableReinitialize Commented Feb 15, 2020 at 19:49
  • if i understand you well, in updateProfile() but my API does not get any response to except status ;), resource link not work with me Your connection is not private
    – Oliver D
    Commented Feb 15, 2020 at 19:53
  • I got your point :))) with newInitialValues but sadly i don't know how can i handle it cuz when i get data from API i push it into an array as you see in getProfileData and after i setState and use it in Formik I use it by index like this initialValues={this.state.initialValues[0]} So have an idea of how can i push an object of data without using an index? The final result should be something like this initialValues={this.state.initialValues}?
    – Oliver D
    Commented Feb 15, 2020 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.