简体   繁体   中英

.then code in the event handler did not run after the submit button is pressed

I have the following code for my React component.


import React, {useRef, useState } from "react"
import { updateUser } from "../api callers/User"
import Loader from "../components/Loader/Loader"
import { useUser } from "./General"

export default function Settings(){

    let user=useUser()

    let reminderViaEmailShouldBeSendTo=useRef<HTMLInputElement|null>(null)
    let reminderViaPhoneShouldBeSendTo=useRef<HTMLInputElement|null>(null)
    let [isSavingSettings, setIsSavingSettings]=useState(false)

    function onsubmit(event:React.FormEvent<HTMLFormElement>){
        event.preventDefault();
        if (reminderViaPhoneShouldBeSendTo.current==null || reminderViaEmailShouldBeSendTo
            .current==null){
               return;
        }

        setIsSavingSettings(true)

        updateUser(user.email, {
            reminderViaPhoneShouldBeSendTo:reminderViaPhoneShouldBeSendTo.current.value,
            reminderViaEmailShouldBeSendTo:reminderViaEmailShouldBeSendTo.current.value
        }, user.authToken).then(
            x=>{
                setIsSavingSettings(false)
            }
        )

    }

    if (user.authToken==""){
        return <Loader></Loader>
    }

    if (isSavingSettings){
        return <div className="center">
            Saving settings ...
        </div>
    }

    return <form className="container" onSubmit={onsubmit}>
        <br></br>
        <label>Reminder via email should be send to</label>
        <br></br>
        <input type="email" ref={reminderViaEmailShouldBeSendTo}
        defaultValue={user.reminderViaEmailShouldBeSendTo}></input>
        <br></br>
        <br></br>
        <label>Reminder via phone should be send to</label>
        <br></br>
        <input type="text" ref={reminderViaPhoneShouldBeSendTo} defaultValue={
            user.reminderViaPhoneShouldBeSendTo
        }
        ></input>
        <br></br>
        <br></br>
        <button className="blue-button" >Save settings</button>
    </form>
}

The code inside updateUser:

export function updateUser(email: string,
  object: { reminderViaEmailShouldBeSendTo?: string, reminderViaPhoneShouldBeSendTo?: string },
  authorizationToken: string) {

  return callAnApiWithSomeJson(urlOfTheServer + "users/" + email, "PUT", authorizationToken, object)
}

The code inside callAnApiWithSomeJson

export function callAnApiWithSomeJson(
  url: string,
  method: string,
  accessToken: string = "",
  json?:Object
) {
  return new Promise((resolve, reject) => {
    console.log(json);
    fetch(url, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type':'application/json'
      },
      method: method,
      body: JSON.stringify(json),
      keepalive:true,
    })
      .then((result) => {result.json().then((result) => resolve(result))})
      .catch((error) => reject(error));
  });
}

When I press the submit button, everything in the onsubmit function in the Settings component runs except for the code in the if statement and the code in the.then block. Why the code in the.then block did not run and how to fix this issue?

I'm writing it here as comments are not suitable for code. Try to simplify your code, so it's easier to debug:

export function callAnApiWithSomeJson(
  url: string,
  method: string,
  accessToken: string = "",
  json?:Object
) {

  console.log('callAnApiWithSomeJson');
  return fetch(url, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
      'Content-Type':'application/json'
    },
    method: method,
    body: JSON.stringify(json),
    keepalive:true,
  })
  .then((result) => result.json());
}

That's all you need for that function. Chaining promises is the way to go, not nesting them.


Apart from that - what browser do you use? keepalive is (or at least was ) known for having issues on various browsers. Try removing it whatsoever.

Also, put logs in your code (if you're not familiar with how to debug it). IF it enters onsubmit and successfully calls callAnApiWithSomeJson , then you'll know where the issue is. Now it's like "I'm calling many things, and something is not working".

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