Self reference model in React Native using MobX-state-tree
While I was programming my mobile application in React Native, using the Ignite stack (i.e. TypeScript and MobX-state-tree), I ran into a specific problem. My api response returns a list of categories and their subcategories, it looks like this:
There’s an interesting case here, because as you can see: in the children
key, we return the same as the parent. How can I declare a model for this answer?
Standard attempt to solve this problem
The first thought comes to us programming it like this:
Unfortunately this cannot be done as the code will not be compiled.
Block-scoped variable 'CategoryModel' used before its declaration. ts(2448)
The good solution to this problem
To program this model correctly, you need to do it like this:
Voilà! You achieved exactly what you wanted. 🙌 Now you can enjoy working and well-written source code.
In this article, I have introduced you to all the tools I use in my work as a full-stack software engineer.
You can also find this article on my software engineering blog where I share my solutions to the problems I encountered during my software engineer career.
If you have additional questions, you can write to me on LinkedIn or Twitter.
Originally published at https://pietrzakadrian.com.