problem trying to initialize and set component state with this axios/typescript implementation - reactjs

I'm trying to use Axios with TypeScript in a React component. The following suggested answer in a different thread seems to provide some pretty good guidance:
https://github.com/axios/axios/issues/1510#issuecomment-385939438
However, something about the suggested approach doesn't appear to be translating well for my component implementation. After fiddling around with this implementation, it seems that I'm still unclear on how state should be initialized in the constructor for this scenario, and possibly within the request().then() handler as well. Here's my current code:
https://github.com/git-it-2020/random/blob/master/axios-react-typescript
The code is fairly simple but doesn't currently compile. Can you provide some guidance on what I'm missing here?

Related

React-Native: When to use Class- or Functional-Components?

I am pretty new to react/react-native and want to develope my first app. During programming I saw that there are two diffrent ways to declare a component. As I understood I always have to use class-components, if I want to access state variables. But according to the react documentations it is also possible to access state variables via useState inside functional-components and now I do not rly know what to use as best practice.
Is there some sort of rule set or coding patterns on when to use class- and when functional-components?
Thank you very much in advance!

Is Flow replace PropTypes?

I'm using React with Flow. If I forgot to set some requiring props when rendering, Flow gives me error so I can prevent the problem.
However Flow is not actually working on runtime. So if the value that I used were treated as number wasn't number, Flow can't catch this. For example, if the value was coming from somewhere else, like server side and if it was string, but Flow just treated as number so eventually I will get some errors in runtime.
But PropTypes works in runtime, so in the same case I'll get the error message that PropType expected number but actually it was string.
It's also possible to happen when the API were changed and returning data is different. It could undefined or whatever, possibly not actual value I expected.
So I'm using Flow and PropTypes both actually, however I searched on about using both together, but couldn't find any related informations.
Instead, all I found was just "Flow" replaces "PropTypes". I don't think so, I already mentioned about difference between these two. These two works totally different and each of them have so many good benefits to use, so combine them will have nice synergy, I think.
However now I'm using both, I have to define types for props and also define propTypes and defaultProps always, and it makes my code actually pretty long and takes lots of time just make single component.
Should I stop using Flow and PropTypes together? I think Flow is better than PropTypes, there were so much benefits when using static type checker so I want to keep using it. Also there's nice VSCode support for Flow, but not proptypes.
If I use Flow, is PropTypes doesn't needed? Any advice will appreciate it.
Flow allows you provide types for anything.
PropTypes is just for component's props so it cannot help with typing variable or method. It even does not have easy way for tyyping callback props. You will need to describe custom validator.
Also PropTypes works on per-prop basis. You cannot describe independent subsets of props. E.g. "having field NAME is required only if nickname is empty". I agree that this sounds not really helpful with this example. But it still means flow is more flexible.
And btw having typecheck in production is bad idea anyway - it would lead to performance penalty. At the same time most type issues will already be caught. While it still does not save you from issues in logic - so you will need to test that with manual/acceptance/integration tests.

Why must I Pass in props to Constructor And Super [duplicate]

This question already has answers here:
What's the difference between "super()" and "super(props)" in React when using es6 classes?
(10 answers)
Closed 4 years ago.
Can someone please tell me why we need to pass in props to constructor() and super(). I've read a lot of questions regarding this, and also a lot articles too. All saying you should pass in props to constructor and super so that you may access this.props.....
All of my code still works if i do not pass in props to constructor or super. And I can't see any scenario where this would change. Unless i wanted to console log this.props, which could be achieved by console logging this anyway.
Also on a side note, half of the developers I've spoken to, do pass in props, and the other half do not, because they feel they don't need to, yet aren't exactly sure why this happens.
Can anyone shed some light on this for me please?
Thanks
The only reason someone needs to pass props is if you want to do something with them in the constructor. Maybe you want to do some computation on props in the constructor -- I'm not sure you can just do that outside of the constructor even though you have access to props without the constructor.
The documentation gives the example of assigning initial state utilizing props in the constructor. In the case of components with local state, this is a good use case for passing props to the constructor.
Additionally, this this SO answer sheds some light on why you need to pass props to super in ES6.
Though, much of this can be disregarded in the sense that you could just not pass props to constructor and initialize your local state without it due to class properties of state and props. Check this Hacker Noon article going through some of the "use cases" of constructor and their alternatives. One thing to point out is that the author mentions that Babel transpiles your code for you to add a constructor -- you just don't see it. Ultimately, I suppose if it is a matter of removing the constructor, you can do it as a matter of preference as also pointed out by Dave Ceddia. Removing the constructor, though, seems to have the added benefit of removing boilerplate and keeping code a bit cleaner.
Ultimately, the author concludes:
We’ve seen that for setting our initial state, we no longer need a constructor (or any other instance property for that matter). We also
don’t need it for binding methods to this. Same for setting initial
state from props. And we would most definitely never fetch data in the
constructor.
Why then would we ever need the constructor in a React component?
Well… you don’t.
[However… If you find some obscure use case where you need to
initialize something in a component, both client-side and server-side,
you still have an out. There’s always componentWillMount. Internally,
React calls this hook right after “newing” the class (which calls the
constructor) on both the client and the server.]
So I maintain that for React components: The constructor is dead, long
live the constructor!

What happens to lifeless react components?

I am right now implementing some kind of notification bubble for users of my webpage.
This bubble usually receives a set amount of time which it is 'alive', as in displayed, until it fades out.
When researching on how to do this fading out, I was usually just trying to figure out how to "remove" a component completely. However, it turns out that this is not the preferred way. The actual solution is to simply manipulate its state so it doesn't render anymore.
At this point I was seriously scratching my head. As I am usually working with languages like C++ or C# I immediately thought what the implications might be, but I didn't find anything.
What does actually happen to components which are in a 'lifeless' state? I mean, they still have to exist, right? Isn't this just polluting memory like crazy?
Thanks in advance!
You'll probably want to use React's Lifecycle Methods to unmount the notification bubble after a set amount of time.
It will be better optimized than having it in a "lifeless state" and only rendering on state or props update.
Edit: This doesn't answer the OP's question and is better served as a comment, I'll be leaving it up until they receive a more appropriate answer

Building mature app architecture based on React/Redux with promises and dependency injection

I'm new to React and trying to get how to build a good app architecture with it.
I also use typescript with all that features: interfaces, async-await, generics, etc. So, I'm puzzled about implementing some patterns:
1) Dependency Injection and reusable component instances
The first thing I can't get through is DI. Let's say we got a component class UserProfile that requires some dependencies like UserProvider. It would be perfect if the component instance (with deps injected) could be reusable, but I'm afraid it's only my dreams, not the react guys'. :)
So, I'm supposed to place this component this way:
<UserProfile id={123} />
Ok, what's the proper way to inject the dependency here? As an attribute like this <UserProfile id={123} dependency={userProvider: userProviderInstance} />?
Don't you think it is weird to put component input data, options/parameters and dependencies all together? I'd be happy if I could clearly separate them and put generic restrictions on the component class. What's the best practice?
Another side of impossibility to reuse component instances is the fact we must carry some needless objects through all the components structure just to inject them somewhere deep at the bottom. And nobody tells you what component does really use them. And try to imagine what adding a dependency to a low-level component will take in a large project. I just can't.
2) Using Promises
Let's consider a simple component that is supposed to render a counter: <Counter value={123} />.
Now, value is got from some API by calling a method getCounter(id: number): Promise<number>;, so the obvious way to put all together could look like this:
<Counter value={await provider.getCounter(id)} />
But i't impossible, I know. The common practice tells us to make it through setState method and rerender the component after the value is received.
Now imagine that the parent component is pretty complex and has many different providers. So, the parent component may not have definite state typing. It also may be conditional, you know...
You could suggest me implement the async getting in the Counter component, but i will refuse for a simple reason: That component does not know anything about the value's origin. In other cases the value is passed directly as a number. So, do you got better ideas how to keep code clean and simple while using promises?
Please, let me know if you come across some good articles or have your own experience in solving these issues.
PS: Thanks for attention! :)
This topic is a subject of bias - so below I will give my very personal thoughts on the topic that does not pretend to be absolute truth.
DI.
This is indeed not so common pattern in react as it is in angular. But having both context and properties in components allows you to archive the same level of separation as with pure DI. Check the context - it will help you to get rid of passing same props through the whole component tree. There are quite a few articles on this topic already (one, two) - check them out. Also you might be interested in reading this thread).
Promises
I do not really see any problem here. React has a simple concept - basically you have state and based on this state your app can render itself. Whereas rendering is not async operation - the preparation/update of the state can easily be done asynchronously and after results are assigned to the corresponding parts of the state - the necessary child components will be updated automatically. If you component has no knowledge of how to obtain value - it should not try to do it in first place - value should be passed down as props.

Resources