How do i use componentWillReceiveProps() correctly? - javascript

I'm trying to update a child component as soon as it recieves new props. However, componentWillReceiveProps() in my child component is called before the props have actually updated. After reading this article i do understand why but it doesn't explain me how to solve my problem.
How do i call componentWillReceiveProps() after the props have updated?
Right now i'm cheating my way around it by letting a timeout run which waits for the actual update, but i really don't like this solution.
componentWillReceiveProps(){
var timeOut = setTimeout(() => this.loadPosts(), 100)
},
Thanks id advance!

Is it necessary to call componentWillReceiveProps after the props have updated? Or can you use the nextProps argument?
Eg. if you rewrite as:
componentWillReceiveProps(nextProps){
this.loadPosts(nextProps)
},
and then of course also rewrite the signature of loadPosts to allow manually passing in props:
loadPosts(props = this.props){
// do something with props
...
}

Use componentDidUpdate(prevProps, prevState). When it's called, two arguments are passed: prevProps and prevState. This is the inverse of componentWillUpdate. The passed values are what the values were, and this.props and this.state are the current values.

Related

How do I tell another component that the setState of useState changes are done so when they get the value it will be the updated value from an event?

Similar to:
How to use `setState` callback on react hooks but I am trying to do this with functional component specifically and I am not trying to replicate the exact same scenario.
React hooks: accessing up-to-date state from within a callback but I am not passing the state from the callback
So say I have a notify() method that I want to be fired AFTER the states have changed, not during state change. Also after I click.
something like
const handleClick = useCallback(()=>{
const [state,setState] = useState("bar");
...
setState("foo", ()=> {
... at this point `state` should be "foo" ...;
notify("yo we're set. but I am not passing the current state to you");
})
});
...
a component that is child of the context
const { state } = useSomeContext();
subscribe(()=>{
console.log("I want ", state, " to be the updated value, but I get the existing value);
});
useStateRef lets the callback know but the ones listening when they query the value that is in the state may not get the updated value.
useStateCallback does not solve the problem for me either because it's the callback that has the value.
The workaround I sort of ended up with (still testing it) is to utilize a useRef to the value somewhat like useStateRef and do stateRef.current instead of just state
When you change the state via the setter, it will cause the current component to re-render. If the component you want to 'notify' is within the current component and has a dependency on the state value that changed e.g.:
return (
<>
<SomeOtherComponent something={state}/>
</>
)
... then that component will re-render as well.
If the component you want to notify isn't in the render path, you can make the state a dependency of a useEffect so your useEffect will run whenever the state change (and do your notification there). You can have multiple useEffects with with dependencies on different state. Example:
useEffect(()=> {
console.log('hello, state is',state)
}, [state])
And you can look into context and other mechanisms to communicate state. You should read this article. I think it's very inline with what you'd like to do.
Certainly don't do anything in your useState setter other than the minimal needed to return the new state.

Why I am getting the old state values after the props change

I just want to understand why in the application I have following situation, below is my constructor of class component:
constructor(props) {
super(props);
this.state = {
tableAlerts: props.householdAlerts,
initialAlerts: props.householdAlerts
}
console.log('householdAlerts', props.householdAlerts)
}
in render function I have:
const { householdAlerts } = this.props;
My issue is that in constructor I got empty array, but in render funtion I have the data. Is it possible to get the data in constructor?
This is a very bad pattern when using the class component. You are ignoring any props updates when you copy the value into state. to manage it:
It requires you to manage two sources of data for the same variable: state and props. Thus, you need to add another render each time your prop change by setting it into state (don't forget to test on equality from prev and next values to avoid being in an infinite loop).
You can avoid setting the state each time your props change by using the getderivedstatefromprops lifecycle method.
So the recommendation is: just use the props; do not copy props into state.
To learn more why you shouldn't, I highly recommend this article.
It is not recommended to set your initial component state in the constructor like so because you gonna lose the ability to use { setState } method after to update this property/state.
The best practice is indeed to refer directly to the prop with { this.prop.householdAlerts }, and keep the state usage for local (or in child components} cases.
if anyhow you want to store props in component state for some reason, call it in lifeCycle -
componentDidMount() {
const { tableAlerts, initialAlerts } = this.props;
this.setState({ tableAlerts, initialAlerts });
}
Hagai Harari is right. Nevertheless, your actual problem seems to be that during your initial rendering the array is empty. Can you ensure that the array has some items, when your component is rendered for the first time?
First rendering -> calls constructor
<YourComponent householdAlerts={[]} />
Second rendering -> updates component
<YourComponent householdAlerts={[alert1, alert2, alert3]} />
If you want initial state to have the prop value.Try something like this with 'this' keyword
constructor(props) {
super(props);
this.state = {
tableAlerts: this.props.householdAlerts,
initialAlerts: this.props.householdAlerts
}
console.log('householdAlerts', props.householdAlerts)
}

Is React's setState() guaranteed to create a new state object every time?

In React, does setState always assign a new object to this.state?
In other words, when you call:
this.setState({
key1: val1,
key2: val2
});
does it always merge the current state object with the new properties into a new object, queueing an operation which is functionally equivalent to the following?
this.state = {
...this.state,
key1: val1,
key2: val2
};
The reason I'm asking is that I'd like to know whether this.state !== nextState is always guaranteed to be true inside shouldComponentUpdate() if the update was triggered by setState.
Thanks.
The simple answer to your question will be "Yes", but for one update cycle. Let me explain this.
As you may already know React setState does not always immediately update the component. Sometimes React batch or defer the updates until later. As an example, let's assume you have something like follows in your event handler.
onClick() {
this.setState({quantity: state.quantity + 1});
this.setState({quantity: state.quantity + 1});
this.setState({quantity: state.quantity + 1});
}
These state update will be queued and execute all together in one update cycle. In such scenario React only create a new state object for the first setState and that object will mutate for subsequent setState updates. You can clearly see this in the source code here.
However, this is something totally about how React works under the hood and we won't need to worry about that. Because there will be only one shouldComponentUpdate() and componentDidUpdate() for one cycle. By the time we access the state it will be always a new object. So we can safely assume that setState() guaranteed to create a new state object every time. But make sure that you aware of other implications of setState which explains in the official documentation.
I'd like to know whether this.state !== nextState is always guaranteed
to be true inside shouldComponentUpdate().
The answer to your this question will be "No" as also explained in other answers. shouldComponentUpdate() will be called because of either state change, props change or both. So this.state !== nextState won't true if the component has updated only because of props change.
I think you want to know the answer to this question.
Will this.state !== nextState is always guaranteed to be true inside
shouldComponentUpdate() ?
According to react docs shouldComponentUpdate will be called on three instance
state changed
props changed
state and props changed
So if only props are changing, your current state will be equal the last unmodified state.
shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.
The first question that you asked are depends on your style of data management for your state.
React lets you use whatever style of data management you want, including mutation.
And the docs also states that
shallow merge of stateChange into the new state, e.g., to adjust a shopping cart item quantity
But looking at the internal parts of setState beginUpdateQueue method let me doubtful when state gets mutated.
I think it would be wise to use immutability-helper for this part of the code, if you must guarantee that no mutation happens to the data.

Re-render component on props update

I guess this is a simple question but here goes: Is there a way of instructing your component to re-render when the props change? I have my component connected to the redux store which on a certain action updates the state, which then filters down into the props, upon which point I want the app to respond to the changes.
I guess you would use componentDidUpdate()?
Something like:
// ...
componentDidUpdate(prevProps, prevState) {
if (prevProps !== this.props) {
// re-render x <-- not sure how to do this
}
}
Plus what would be the method to re-render the whole component, and what would be the method of re-rendering only the updated props?
Any help appreciated.
You can call this.forceUpdate() in the method. Another way is this.setState(this.state).
You can use
componentWillReceiveProps (props){
this.doSomething(props) // To some function.
this.setState({data: props}) // This will update your component.
}
If your props is something that needs to change the state you will get an infinity loop.
Check out Reacts life cycle here by the way, might help aswell.

React - updating state during render produces errors

I'm new to React and am trying to update the state of a parent component from the child everytime an onChange action happens. The onchange action comes from an input box that when letters are typed it updates the state of searchInputVal with the value of what has been typed. I have a parent <App/> component with the following properties and states here:
updateSampleFilteredState(filteredSamples) {
this.setState({
samples: filteredSamples
});
},
getInitialState () {
return {
samples:allSamples,
searchInputVal:""
}}
I pass the properties and states down to a child component here:
updateNewSampleState(filteredSamples){
return (
this.props.updateSampleFilteredState(filteredSamples)
)
}
render() {
const filteredSamples = this.props.samples.filter(sample => {
return sample.sampleFamily.toLowerCase().indexOf(this.props.searchInputVal.toLowerCase()) !== -1;
});
this.updateNewSampleState(filteredSamples);
return <div className="samples-container-inner-styling">
{
filteredSamples.map((sample) => {
return (...
Before I added the line this.updateNewSampleState(filteredSamples); the child component would render out the filtering just fine but obviously not update the state of sample with the new filtered state. When I the line this.updateNewSampleState(filteredSamples); to execute the function in the component to set the new state I get a list of re-occuring errors that eventually make my app crash. The errors say something about an anti pattern. I'm not sure how else to update the state?
You should't be updating the state from the render function, and you are facing the reason why that's a bad way to do things. Every time you call the setState the component re-renders, so if you call it inside the render function it will be called again and so on... You should ask yourself why are you calling that function there. I guess you could just do it in the onChange function you are using for the input.
As already mentioned by #César, setting the state in the renderer doesn't make sense, since setting the state triggers a rerender of the component, so you basically get something like an infinite render loop.
Given that you are computing filteredSamples only from the props, you could compute that state in the constructor:
The constructor is the right place to initialize state.
However, note the following when deriving state from props in the constructor:
It's okay to initialize state based on props if you know what you're doing. [...]
Beware of this pattern, as it effectively "forks" the props and can lead to bugs. Instead of syncing props to state, you often want to lift the state up.
If you "fork" props by using them for state, you might also want to implement componentWillReceiveProps(nextProps) to keep the state up-to-date with them. But lifting state up is often easier and less bug-prone.

Categories

Resources