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

Several lazy hooks to the same variable/state? #176

Closed badtant closed 4 years ago

badtant commented 4 years ago

Kind of new to hooks so forgive me if this is obvious to you how to do :)

Can I have two lazy hooks that stores the result in the same variable "myData"? Or should/can I use a state (useState or useReducer) and set/dispatch the data from useGet to that state?

const { data: myData, refetch: fetch1 } = useGet({
    path: "/list1",
    lazy: true
  });

const { data: myData, refetch: fetch2 } = useGet({
    path: "/list2",
    lazy: true
  });
TejasQ commented 4 years ago

Hi @badtant! Thanks for asking!

You can't redefine myData in this case because it is a constant: you define it in line 1, and so it cannot be redefined.

It seems to me like you'd like to have one list populated by both requests? If that's correct, I'd suggest having a list as part of your component's state, via useState or similar, and then setting it after the request completes, like this:

const [myTotalData, setMyTotalData] = useState([]);

const { data: myFirstData, refetch: fetch1 } = useGet({
    path: "/list1",
    lazy: true
  });

const { data: mySecondData, refetch: fetch2 } = useGet({
    path: "/list2",
    lazy: true
  });

// somewhere in your app where you call fetch1
fetch1()
  .then(response => setMyTotalData([...myTotalData, response]));

// somewhere ELSE in your app where you call fetch2
fetch2()
  .then(response => setMyTotalData([...myTotalData, response]));

This way, myTotalData will contain the some of both lazy fetches.

What questions do you have about this approach? Happy to expand further if any.

Appreciate you, @badtant! 💞

badtant commented 4 years ago

Cool, thank! Will this generate more re-renders than needed? I'm guessing that both useGet and then setMyTotalData will trigger renders. Is there a way to stop useGet from causing a render?

TejasQ commented 4 years ago

Tbh rerenders are not something you should have to worry about. The React core team are spending time and effort to provide a consistent experience no matter how many renders happen.

That's also on us as library authors. I'd suggest going with this approach, focusing on your app, and letting us worry about optimizations so that you can focus on your task at hand.

badtant commented 4 years ago

Thats the kind of reply I like :)