1

I'm working with react Navigation 5.x. My requirement is to create a screen having multiple material top tabs inside one of stack navigation screens. enter image description here

When the Clinics screen is opened, an API needs to be called to set some data as state and the data needs to be shared across all three tabs(example: if API returns 10 numbers, all even numbers to be listed in tab 1 and odd ones in tab 2).

How do I achieve this? Thanks in advance.

Dinesh Babu
  • 73
  • 1
  • 1
  • 7
  • 1
    Does this answer your question? [Global state in React Native](https://stackoverflow.com/questions/44227235/global-state-in-react-native) – Cornel Raiu Jul 21 '20 at 18:57
  • Thanks for your time, Cornel. I have a vague idea that reducer/context must be used. But, I'm failing to put it on paper. – Dinesh Babu Jul 21 '20 at 19:14
  • I was actually carried away by the navigation.setParams() and mostly overlooked context for a bit. I'd giving a try on context and hooks. Thanks. – Dinesh Babu Jul 22 '20 at 08:12

1 Answers1

1

I was carried away by the navigation.setParams() and overlooked react hooks.

Achieved the required with the useContext, useState and useEffect.

Added a ClinicsProvider.js that creates context, useState to maintain state of data, useEffect to make api call and setData. Wrapped the ClinicsProvider around stack navigator which contains tab navigator. Each tab screen then import the ClinicsContext by using the useContext hook and access the API data.

Dinesh Babu
  • 73
  • 1
  • 1
  • 7
  • I think this is a good answer, this was the approach I was thinking of taking for this problem too. I think using `setParams` here would be waaay too limited if you want to share calls and state. – JoniVR Nov 04 '20 at 15:05
  • Yes this is indeed a good approach. navigation params is limited in the context where the data being passed as params changes. In the case of using a snapshot(updating data), params will only send the data once but doesn't update the snapshot data – Lakshman May 04 '21 at 22:52