简体   繁体   中英

How to return boolean from async await function instead of Promise<boolean> (Typescript | React)

So i'm working in React.js and i have a Calendar Component from AntDesign that includes a disabledDate prop.

This disabledDate prop recieves a boolean as response and it checks every date from the Calendar Component.

The thing is that my client gave me an API that sends me a 200 response if it finds some data (it means that the Date is available for scheduling) and a 404 response if it don't

So what i'm doing is that i created a function that checks if a given date is available or not and based on the result from this function, the disabledDate prop will enable or disable a Date from the Calendar component.

The problem now is that disabledDate can't recieve a Promise, it needs a Boolean, and when i turn it into async it obviously would return a Promise instead of a Boolean.

Is there any workaround or i'm missing completely the point

This is my function

 export const isDateAvailable = async ( specialistID: number | undefined, serviceID: number | undefined, date: moment.Moment ) => { const body = { especialista_id: specialistID, servicio_id: serviceID, fecha: date.format("YYYY-MM-DD"), }; const response = await axios.get(API_URL + "/disponibilidadAtencion", { params: body, }); if (response.status === 404) { return false; } return true; };

This is my Calendar Component

 <Calendar fullscreen={false} mode={"month"} disabledDate={async (current) => { if (current.fromNow() === "a few seconds ago") return false; const dateAvailability = await isDateAvailable( selectedSpecialist?.especialista_id, selectedService?.servicio_id, current ); console.log(dateAvailability); return current < moment() || !dateAvailability; }} />

The ideal way would be use state variable to hold isDateAvailabe() response and use the state variable inside the Calendar component.

The other thing you need to decide, how should be component behave while you function isDateAvailable() is resolving. It can either be hidden or in disabled state, depending on your use case.

Below code sample you can use for your reference, its disable the calender component while api call is fetched.

export default CalendarWrapper = () => {
  const [isDisabled, setDisabled] = useState(false)
  
  useEffect(() => {
   isDateAvailable(
        selectedSpecialist?.especialista_id,
        selectedService?.servicio_id,
        current
    ).then (dateAvailability => {
      setDisabled(current < moment() || !dateAvailability)
    });
  }, [])

  return (
  <>
    <Calendar
    fullscreen={false}
    mode={"month"}
    disabledDate={isDisabled}
    />
  </>
)
}

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