简体   繁体   中英

React Synchronous Api Calls (call second api after Cloudinary image upload call finishes)

I've been trying to do two api calls synchronously on form submit, the first one adds an image to my Cloudinary library and gets a url so I can display that image. The second api call is supposed to add a post object to my database after the first one is finished.

This is an example of a form that I want to handle both api calls, although the image is uploaded to my Cloudinary library, this current form leaves the imgUrl variable in my database empty when submitted. I'm assuming it does this because the first api call(uploadImage) doesn't finish before the second one(addPost) is called.

<form action="" onSubmit={e => handleSubmit(e.target)}>
    <input type="text" name="text"/>
    <input type="file" name="file" id="file" onChange={e => setImageSelect(e.target.files[0])}/>
    <button type="submit">Submit</button>
</form>

This is an example of a form that works as expected but allows the user to upload multiple images to my Cloudinary library before submitting the form. I only want to allow the user to upload images after submitting the form though, like the form above.

<form action="" onSubmit={e => addPost(e.target)}>
    <input type="text" name="text"/>
    <input type="file" name="file" id="file" onChange={e => setImageSelect(e.target.files[0])}/>
    <button onClick={uploadImage}>Add image</button>
    <button type="submit">Submit</button>
</form>

These are the functions that are being called in the form:

const handleSubmit = (form) =>{
    uploadImage();
    addPost(form);
}

const uploadImage = async () =>{
    const data = new FormData();
    data.append('file', imageSelect);
    data.append('upload_preset', 'UPLOAD_PRESET');

    try {
        const response = await axios.post('https://api.cloudinary.com/v1_1/LIBRARY_NAME/image/upload', data);
        const file = response.data;
        setImage(file.secure_url);
    } catch (err) {
        console.error(err);
    } 
}

const addPost = async(form) =>{
    try {
        await axios.post('/.netlify/functions/add', {
            text: form.text.value,
            imgUrl: image
         });
    } catch (err) {
        console.error(err);
    } 
    fetchData();
}

Does anyone have an idea why the first form isn't working as expected?

You can add a useEffect hook to check if the imageURL is achieved and then fire the save function which stores the url to the database.

useEffect(() => {
    if(image){
        addPost();
    }
}, [image]);

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