setState wants me to specify ALL properties of my state interface? - reactjs

I'm using React 15 and TypeScript 1.8.
My component's state object has multiple properties. I define an interface describing their types, write my component with class MyComponent extends React.Component<any, MyStateInterface>, set initial values for every property in the constructor method, it's all good.
The problem I have is when calling this.setState to update only one of my properties. TypeScript complains that I'm not setting all of them ("Property missing" error). I searched StackOverflow for a solution, and found others complaining of this, saying that the only solution was to simply declare all the fields optional.
However, that was an 18 month old answer, and I know both TypeScript and React move fast. I'm just wondering if this has changed in the last 500 days, and what the recommended practices are?

The problem I have is when calling this.setState to update only one of my properties. TypeScript complains that I'm not setting all of them
You should mark all of the members of the state as optional.
You might think this would be unsafe ... but because of freshness more it is still typechecked.

Related

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!

Is it important when using React propTypes validations to check them at every level?

I'm working on a part of a React app in which a high-level component creates and passes certain props down through a few layers of components that don't use them to a final component that does.
When validating props with propTypes, is there a good reason to list these props to be checked at every level, going down through the layers? Or is it acceptable to check them only in the final component that uses them?
It seems to me that the former method is redundant; the latter seems to make more sense to me, but I'm curious if there is a reason why I ought to do the former. I haven't seen any discussion on it, which could mean it's an unimportant question, but I'd be interested to know.
I agree with you about if you use props only for dril down for children in the tree, it can be done only once at the leaf components, where you realy use this data. I recently find out that one more place is important for props validation: the components which fetch data from out of app scope, such as backend, because sometimes the structure of the data changes or the data types, then it will be dificult to find which part is broken without props validation.

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.

Detecting rather prop were passed in or set by defaultProps

I would find it convenient if one of two closely related features were possible to do in React, purely for convenience/syntactic sugar since I know I can do what I want without them, it's just a little uglier/slower. I suspect neither can be done, so rather then write two separate questions that are nearly identical I'm asking about both in this question so you can crash my dreams all at once :)
I've found myself wanting a convenience feature a few times, some way of storing in props a little more knowledge about what props are set to avoid having to write as many helper methods.
To use my most recent example I have two props errorEvaluator and warningEvalutator are functions that check rather a data set should be marked with warning or error state. They both have default props which always return false if an evaluation isn't provided, so I don't have to constantly do null checks in code.
I now want to know if no warning or error evaluator was provided, if so I won't offset everything to make space for the warning/error icon that will never be used, I can't just check for the funcitons being undefined since I use defaultProps. What I'd like is one of two quickconvenience options for checking if these values weren't set by the operator. So something like:
some function that checks rather a prop was passed by user, as opposed to being set by default props, I could call to find out rather there was a value set.
Some way to do quick modification of props whenever a component updates where I can set some showIcon prop if both evaluators are undefined, then set the evaluators to my default always-false evaporators; without having to resort to lifecycle methods which somehow feel like overkill.
Do either of these, or some equivalent quick way of doing such a check exist?
The cleanest option I know works is to not use default props and instead have methods that return my evaluators, returning default evaluator if none is passed, for when I want to use an evaluator, then checking for undefined evaluator in props when I want to know if an evaluator was provided. That works, I'm just wondering if there is some quicker or cooler syntactical sugar I'm not aware of?
For point 1: you can't check whether a prop was passed in or set by default, as doing that would defeat the entire point of having default props. If you want to be able to tell whether a prop was passed in or not, you must not use a default prop and check for undefined.
As for point 2: Not only is there no way to do that, but you should never change props from within the component that receives them. That's just against the way that React works. A component should take its props and handle them. If some value or UI element is an "output" of a component and computed from its props, it should not be a prop of that component. If you need to detect when props change, then lifecycle methods aren't overkill, they are the right way to do that.
Since you know which functions are the default ones, you can check for them explicitly. You could use an equality comparison:
if(this.props.errorEvaluator === this.defaultErrorEvaluator) {
// Set up styles to exclude formatting
}
You'd need to go slightly out of your way to ensure that you always used exactly that evaluator, and that the caller didn't get their hands on it, but that shouldn't be hard.

Is this valid reactJS code?

New to ReactJS. Got this on a "join reactJS event questionary" but was unable to compile it. It seems to be missing a React Component class definition for the Item and List.
Is this shorthand style valid?
Is this shorthand style valid?
yes, it is valid code, List and Items are Stateless functional components
In order to run this code you need use babel with babel-preset-react
Yes, they are stateless functions, aka "pure components". They take their props as their only parameter and return the render results. If you do not need to keep track of any state, they are very lightweight both to understand mentally and in terms of the resources needed by React to manage them.
As to why you were unable to compile it, possibly you do not enable the right ES6/ES2015 features in whichever compiler you're using. You are using among other things super calls, object destructuring (in the parameters) and arrow functions. For help with this, provide the specific error message.
It is a valid javascript es6 code, except that multiple dynamic children (here the list of Items) need to have key prop https://facebook.github.io/react/docs/multiple-components.html#dynamic-children

Resources