financial_physician
financial_physician

Reputation: 1998

How to best to listen for POST response in react?

I have data in a form that I'd like to load to a database and depending on the state either keep them on the page or move them to a different page.

currently I have the following function attached to the form.

const handleSubmit = (e) => {
        e.preventDefault();
        const topic = {id, title, desc, text};
    
        console.log(topic);
        
        const isSuccess = commitData(topicsEndPoint, topic)
        console.log(isSuccess)
        if (isSuccess) {
            history.push(endPoint)
        } else {
            setError("An error has occured.")
        }
    }

And commitData is ran like this...

export const commitData = (endPoint, data) => {
    let isSuccess = false;

    fetch(endPoint, {
        method: 'POST',
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify(data)
    })
    .then(e => {
        if (!e.ok) {
            throw(e)
        }
        isSuccess = true;
        console.log(isSuccess)
        return isSuccess
    })
    .catch(err => {
        isSuccess = false;
        console.log(isSuccess)
        return isSuccess
    })
}

I believe I could get it to work if I passed history and the redirect page into commitData but that starts to become more cumbersome than the functions already look.

Right now this doesn't work because handleSubmit doesn't wait for a response to come back before moving on.

I think using a hook is the way to go but react doesn't like it because I have it inside handleSubmit but even when I capitalized it HandleSubmit it didn't like it.

I'm looking for what the best practice would be.

(I tried await and then attached to commitData but it didn't like the syntax)

Upvotes: 0

Views: 858

Answers (1)

k-wasilewski
k-wasilewski

Reputation: 4653

Make handleSubmit() async:

const handleSubmit = async (e) => {
        e.preventDefault();
        const topic = {id, title, desc, text};
    
        console.log(topic);
        
        const isSuccess = await commitData(topicsEndPoint, topic)
        console.log(isSuccess)
        if (isSuccess) {
            history.push(endPoint)
        } else {
            setError("An error has occured.")
        }
    }

Upvotes: 1

Related Questions