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

Please help me handle events correctly #246

Closed webwmagnet closed 4 years ago

webwmagnet commented 4 years ago

Thanks Thank you very much for this amazing library, it is very cool!

Problem I just started working with her, so I had difficulty with mutations.

An array arrives from the server, they have a method, deletion. I do not know how to properly handle this event.

Attached a screenshot of how I did it, but I really do not like my way, it is somehow wrong.

I also thought of writing these events to useState, after already deleting them locally through the filter, but this also seems too not very.

Please tell me how to correctly handle click requests that will show the correct, new data?

P.S. I write poorly in English, so this is all a translator, sorry!

Screenshots Alt text

fabien0102 commented 4 years ago

You can remove the useEffect and the lazy: true, this should do the same. Otherwise the logic is correct, you delete and refetch to have the new data.

You can also have a copy of the "data" to a state, so you have some optimistic response, something like this:

const [events, setEvents] = useState([])
const { data, refetch } = useTimeline()
const { mutate: deleteEvent } = useDeleteEvent()

useEffect(() => {
  setEvents(data)
}, [data])

const deteleHandler = (id) => {
   // Optimistic part
   setEvents(prev => prev.filter(e => e.id != id))

  // API part
  deleteEvent(id)
  .then(refetch)
}

But this is just for optimisation, totally not necessary 😉

PS: I'm responding from my phone, so sorry if the code example is not perfect ^^

webwmagnet commented 4 years ago

@fabien0102 Thanks a lot! You are a genius, even write a code from your phone without any IDE, etc.