简体   繁体   中英

How to achieve an async function chain with await when the functions are parent and child?

I have a profile editor component (parent) and a cropper component (child). I want to update a database with two async actions awaiting each other. These are: 1.) a dispatch from the parent, which has form fields, and 2.) a dispatch from the cropper, which has an image blob. At the moment I have a parent file, a child file, and an actions file.

relevant snippet from parent:

 handleSubmit = e => {
    e.preventDefault();
    // Dispatches action to update database with form fields
    this.props.accountSettingsUpdateProfile(this.state);
  };

relevant snippet from child:

  onClickSave = () => {
      if (this.editor) {
        this.editor.getImageScaledToCanvas().toBlob(blob => {
        // Dispatches an action to upload database with new cropped image
        this.props.uploadProfileImage(blob);
      });

And in my actions file I have something like:

export const accountSettingsUpdateProfile = settings => async () => {//etc}

export const uploadProfileImage = file=> async () => {//etc}

I would like to have something like:

Parent

handleSubmit = e => {
    e.preventDefault();
    // Dispatches action to update database with form fields
    this.props.dispatchParentFieldsAndChildBlobToActions();
  };

Actions

  try {
      //Both try update, if either error logged to console.
      } catch (error) {
    console.log(error)
  }

The crux of it is, I don't know how to consolidate these actions. I could achieve what I want by just cutting the cropper component out and pasting it into it's parent instead of having it as a separate component, but that's cheating.

An alternate approach would be like this. Save child and parents relevant states to redux store then call your actions upon a button click or something in parent or child whenever you need it.

your parent or child components

handlSubmit=()=>{
this.props.saveMyProfile((info)=>console.log(info)); //you can passs a callback if you wish
}

Actions.js

export const saveMyProfile = (callback) => async (dispatch, getState) => {
try {
    const profileData= getState().profile.data; //get data from your redux store
    const blob= getState().profile.blob; 

    if (!profileData || !blob){
     callback("either profile data or blob is empty");
     return;
    }

    const response = await axios.get(baseURL, { profileData,blob });
    // console.log("data: ", response.data);

    dispatch({ type: SET_PROFILE_DATA, payload: null });
    callback("profile has been successfully updated!");
  } catch (err) {
    console.log(err);
   callback("error occured!");
  }

}

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