简体   繁体   中英

Can't save state in React while POST API request

I have handleSubmit function that send two POST request, one for img upload and one for other information. I want to take the response from the img upload request and take the 'filename' and then store it in state so I can sent it with the other POST request.

Here is my Request Options

const postOptions = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.serviceToken}`
    },
    body: JSON.stringify({
        p_emp_id: empId,
        p_pr_doc_type: docType,
        p_from_date: fromDate,
        p_to_date: toDate,
        p_doc_number: docNumber,
        p_addres: address,
        p_addres_en: addressEN,
        p_doc_store: docPath,
        p_creator_id: creator,
        p_org_id: org
    })
};

Then here is my Handle Submit function

const handleSubmit = async (e) => {
    e.preventDefault();
    const data = new FormData();
    data.append('file', selectedFiles);
    await fetch(`${config.apiHost}single/`, {
        method: 'POST',
        body: data
    })
        .then((res) => res.json())
        .then((img) => setDocPath(img.filename))
        .catch((err) => {
            console.log(err.message);
        });
    setEditOpen(false);
    fetch(`${config.apiHost}api/employees/info/pr_docs/new/`, postOptions);
    console.log(postOptions.body);
};

My state stays empty while I submitting so after that I can't see it in my request. Please help

you can refactor your code to this and lets see if it works;

let postOptions = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.serviceToken}`
    },
    body: {
        p_emp_id: empId,
        p_pr_doc_type: docType,
        p_from_date: fromDate,
        p_to_date: toDate,
        p_doc_number: docNumber,
        p_addres: address,
        p_addres_en: addressEN,
        p_creator_id: creator,
        p_org_id: org
    }
};

for the handle submit it can be

const handleSubmit = async (e) => {
    e.preventDefault();
    const data = new FormData();
    data.append('file', selectedFiles);
    await fetch(`${config.apiHost}single/`, {
        method: 'POST',
        body: data
    })
        .then((res) => res.json())
        .then((img) => {
const postOptionsBody = {...postOptions.body, p_doc_store : img.filename }

postOptions = {...postOptions, body : JSON.stringify(postOptionsBody) }
setDocPath(img.filename)
})
        .catch((err) => {
            console.log(err.message);
        });
    setEditOpen(false);
    fetch(`${config.apiHost}api/employees/info/pr_docs/new/`, postOptions);
    console.log(postOptions.body);
};

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