contiamo / restful-react

A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs 🔥
MIT License
1.87k stars 109 forks source link

make loading state an enum #236

Closed cztomsik closed 4 years ago

cztomsik commented 4 years ago

Is your feature request related to a problem? Please describe. Sometimes you want to not only show spinner when something is loading but also show some (component-local) notification if it has been done successfully.

Right now, you need to introduce your own state + callback which will call mutate and update the state.

This would be useful for contact forms, password resetting and probably some other cases too.

Example:

import React, { useState } from 'react'
import { useForm } from 'react-hook-form'
import { useMutate } from 'restful-react'

const ContactForm = () => {
  const { register, handleSubmit } = useForm()
  const { mutate, loading } = useMutate({
     verb: 'POST',
     path: 'contact-form'
   })

  // all of this could be removed
  const [done, setDone] = useState(false)
  const submit = async (data) => {
    setDone(false)
    await mutate(data)
    setDone(true)
  }

  return (
    <form onSubmit={handleSubmit(submit)}>
      {loading && 'Please wait...'}
      {done && 'Message sent'}
      <textarea ref={register} name="message"></textarea>
      <button>Submit</button>
    </form>
  )
}

Describe the solution you'd like

fabien0102 commented 4 years ago

So, sorry for the late response (kind of a busy life over there 😉), I check a bit our implementation and your usecase, and I found something that I totally forgot that should fit your usecase!

We have a onMutate callback on useMutate, called just after the mutation.

So I guess we should be able to do something this:

import React, { useState } from 'react'
import { useForm } from 'react-hook-form'
import { useMutate } from 'restful-react'
import { useNotification } from "./myNotif"

const ContactForm = () => {
  const { register, handleSubmit } = useForm()
  const { infoNotif } = useNotification();
  const { mutate, loading } = useMutate({
     verb: 'POST',
     path: 'contact-form',
     onMutate: (body, data) => infoNotif("Done");
   })

  return (
    <form onSubmit={handleSubmit(mutate())}>
      {loading && 'Please wait...'}
      <textarea ref={register} name="message"></textarea>
      <button>Submit</button>
    </form>
  )
}

Note: I don't really know how react-hook-form is working ^^

Is this could solve your issue?

cztomsik commented 4 years ago

For most cases, probably yes, thanks!