简体   繁体   中英

How to re-render Formik values after updated it - React Native?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM