0

Hey I am testing several frameworks for hybrid mobile development. All in all I like React Native a bit more than Angular, but I like the mechanism of Injector and Provider very much. To have a single instance of a class could be very usefull, but at the moment I don't know how to realize that with React Native. I thought about to use the AsyncStorage, but I am not happy with that. The key question: Is there a way to use the same instance in several components in React Native?

I thought about Singleton, but don't know how to realize that.

peni4142
  • 426
  • 1
  • 7
  • 26

2 Answers2

0

React just gives you a component layer. They don't provide dependency injection. You need to implement by your own and it's very hard to implement as Angular provides a single instance for a service no matter how many places you used service. For singleton like pattern you need to create a class and will ask to that class to give you an instance of service. This class will take care. If an object already exist of your service then it will return existing object otherwise will create a new object.

Sandip Jaiswal
  • 3,428
  • 2
  • 13
  • 15
  • I have learned programming with C#. I don't know all basics about javascript yet. I not know how to creat this class, which notices that instance already exists. I think, if I create a component which can handle instances and I import that component in two other components, I would have two components which would handle the instances seperatly. Or could I create a component with a static variable, which is the same for all imports of that component? PS: I hope my english is not too bad :-) – peni4142 Dec 20 '17 at 12:43
  • Just create a Class and use static variable that will be instance of your service. But that will not a good use case. I think you should create a static method and a static variable of type of your service. Initially this variable will hold a null value. When you will need a instance of service just call the method. This method will check if variable is null then it will create an object otherwise will return existing object. Hope it will help – Sandip Jaiswal Dec 20 '17 at 12:57
0

You can use mobx.

See example here: https://github.com/PrioritySoftware/priority-master-react/.

What I did was defining my providers in src/providers/index.ts and then passing the instance to the components using Mobx.

Take a look at these two files:

1) src/app.tsx.

2) src/pages/main.page.tsx.

The injection itself: https://github.com/PrioritySoftware/priority-master-react/blob/master/src/pages/main.page.tsx#L29.

I actually started with Angular and then got to know React :)

neomib
  • 3,503
  • 4
  • 17
  • 27