I'm getting the following error:
Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
My component:
import React from 'react';
import { Redirect } from 'react-router'
import Notifications from 'react-notification-system-redux';
constructor(props) {
super(props);
this.state = {
invite_token: this.props.match.params.token,
FormSubmitSucceeded: false,
inviteRequestSubmitSucceeded: false
};
}
....
inviteAlreadyUsed() {
const notificationOpts = {
message: 'Invitation already used!',
};
this.props.createNotificationSuccess(notificationOpts);
}
render() {
const { invite } = this.props;
if (invite && invite.status === "completed") {
this.inviteAlreadyUsed();
return <Redirect to={{ pathname: '/' }}/>;
}
...
Any suggestions on how to avoid this warning? Is this not how you would handle a redirect?
this.inviteAlreadyUsed(); in render -> reducer updating a state -> it call new render -> this.inviteAlreadyUsed(); -> reducer update a state and again and again...
Just don't call inviteAlreadyUsed in render.
First, I think you should bind the inviteAlreadyUsed() function. You can use arrow function () => {}.
inviteAlreadyUsed = () => {
const notificationOpts = {
message: 'Invitation already used!',
};
this.props.createNotificationSuccess(notificationOpts);
}
Second, seems like you set the state with props in constructor. Setting it in componentWillMount() might be a better approach.
constructor(props) {
super(props);
this.state = {
invite_token: '',
FormSubmitSucceeded: false,
inviteRequestSubmitSucceeded: false
};
}
componentWillMount() {
this.setState({
invite_token: this.props.match.params.token
})
}
Related
When I use fetch in setState the function makes two network requests, but I expect one request.
Why is this happening and how to prevent it?
import React from 'react';
class TestFetch extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(() => {
fetch('http://example.com/', {
mode: 'no-cors'
})
.then(data => {
console.log(data)
});
});
}
render() {
return (
<button onClick={this.handleClick}> Test </button>
)
}
}
export default TestFetch
Another version with setState in the fetch. Now I have one network call, but two values in my state after one click:
import React from 'react';
class TestFetch extends React.Component {
constructor(props) {
super(props);
this.state = {
'newItems': []
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
fetch('http://example.com/', {
mode: 'no-cors'
})
.then(data => {
this.setState((state) => {
state.newItems.push("value")
})
console.log(this.state)
});
}
render() {
return (
<button onClick={this.handleClick}> Test </button>
)
}
}
export default TestFetch
Ok, basically it has this effect in this example as well:
import React from 'react';
class TestFetch extends React.Component {
constructor(props) {
super(props);
this.state = {
'newItems': []
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => {
state.newItems.push("value")
})
console.log(this.state);
}
render() {
return (
<button onClick={this.handleClick}> Test </button>
)
}
}
export default TestFetch
Don't do api call in setState.. take state variable and store api response data in it and use state variable when ever it's required.
import React from 'react';
class TestFetch extends React.Component {
constructor(props) {
super(props);
this.state = {appData: null};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
fetch('http://example.com/', {
mode: 'no-cors'
})
.then(data => {
console.log(data)
this.setState(() => {appData: data});
});
}
render() {
return (
<button onClick={this.handleClick}> Test </button>
)
}
}
export default TestFetch
Why is this happening...
My guess would be you are rendering your app into a React.StrictMode component. See Detecting unintentional side-effects
Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method
Function component bodies
State updater functions (the first argument to setState)
Functions passed to useState, useMemo, or useReducer
In other words, the setState is called twice by React to help you find unintentional side-effects, like the double fetching.
...and how to prevent it?
Just don't do side-effects in the setState callback function. You likely meant to do the fetch and in the Promise chain update state.
handleClick() {
fetch('http://example.com/', {
mode: 'no-cors'
})
.then(data => {
console.log(data);
this.setState( ......); // <-- update state from response data
});
}
Update
Another version with setState in the fetch. Now I have one network
call, but two values in my state after one click:
In your updated code you are mutating the state object. Array.prototype.push updates the array by adding the new element to the end of the array and returns the new length of the array.
Array.prototype.push
this.setState(state => {
state.newItems.push("value") // <-- mutates the state object
})
I believe you see 2 new items added for the same reason as above. When updating arrays in state you need to return a new array reference.
You can use Array.prototype.concat to add the new value and return a new array:
this.setState(prevState => {
newItems: prevState.newItems.concat("value"),
});
Another common pattern is to shallow copy the previous state array into a new array and append the new value:
this.setState(prevState => {
newItems: [...prevState.newItems, "value"],
});
Additionally, once you sort out your state updates, the console log of the state won't work because React state updates are asynchronously processed. Log the updated state from the componentDidUpdate lifecycle method.
componentDidUpdate(prevProps, prevState) {
if (prevState !== this.state) {
console.log(this.state);
}
}
I am getting this error below:
react_devtools_backend.js:2430 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
From the error, I know I am getting it because I am setting state in the render.
But I am not sure where to set the state because I need that state element, developerTitle further down inside the render method.
Where can I put it if not in render?
Thanks!
Here is my code:
export default class Game extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
developerTitle: ''
}
}
render() {
const { indieDeveloperId } = this.props;
this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
<div>
<h3>{this.state.developerTitle}</h3>
...
...
</div>
}
//by-indie-developer/{indieDeveloperId
async getDeveloperTitle(indieDeveloperId) {
const r = await axios.get(`/api/developer/by-indie-developer/${indieDeveloperId}`);
const developerTitle = r.data;
this.setState({
...this.state, ...{
developerTitle: developerTitle
}
});
}
}
You can't set a state in render(). But you can set a state when the component is loaded using the componentDidMount() function.
Add a function with that name like this to your component:
componentDidMount() {
this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
}
You dont have to call the function. The state will automatically be set.
This app is supposed to filter words by a specific input. I want to call a function with setState() when rendering a component and technically it's working but there is warning in the console.
Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
I guess that this is because I'm calling the function in the render function which I shouldn't, but what should I do instead?
class UsersList extends React.Component {
constructor(props) {
super(props);
this.state = {
allUsers: ["Michał", "Ania", "Kasia", "Tomek", "Hubert", "Jan", "Martyna", "Rafał", "Bartłomiej"],
filteredUsers: [],
input: null
}
}
filter() {
if (this.state.input !== this.props.inputValue) {
const filtered = this.state.allUsers.filter(user => user.toLowerCase().includes(this.props.inputValue));
this.setState({
filteredUsers: filtered.map(user => <li key={user}>{user}</li>),
input: this.props.inputValue
})
}
return this.state.filteredUsers;
}
render() {
this.filter()
return (
<ul>
{this.state.filteredUsers}
</ul>
)
}
}
class App extends React.Component {
constructor() {
super();
this.state = {input: ""};
this.handleInput = this.handleInput.bind(this);
}
handleInput(e) {
this.setState({input: e.target.value})
}
render() {
return (
<div>
<input onChange={this.handleInput} type="search"/>
<UsersList inputValue={this.state.input} />
</div>
);
}
}
The issue here is caused by changes being made to your component's state during rendering.
You should avoid setting component state directly during a components render() function (this is happening when you call filter() during your component's render() function).
Instead, consider updating the state of your component only as needed (ie when the inputValue prop changes). The recommended way to update state when prop values change is via the getDerivedStateFromProps() component life cycle hook.
Here's an example of how you could make use of this hook for your component:
class UsersList extends React.Component {
constructor(props) {
super(props);
this.state = {
allUsers: ["Michał", "Ania", "Kasia", "Tomek",
"Hubert", "Jan", "Martyna", "Rafał",
"Bartłomiej"],
filteredUsers: [],
input: null
}
}
/* Add this life cycle hook, it replaces filter(). Props are updated/incoming
props, state is current state of component instance */
static getDerivedStateFromProps(props, state) {
// The condition for prop changes that trigger an update
if(state.input !== props.inputValue) {
const filtered = state.allUsers.filter(user => user.toLowerCase().includes(props.inputValue));
/* Return the new state object seeing props triggered an update */
return {
allUsers: state.allUsers
filteredUsers: filtered.map(user => <li key={user}>{user}</li>),
input: props.inputValue
}
}
/* No update needed */
return null;
}
render() {
return (<ul>{this.state.filteredUsers}</ul>)
}
}
Hope this helps
The error is coming up as it could create an endless loop inside the component. As render method is executed whenever the state is updated and your function this.filter is doing a state update. Now as the state updates, your render method triggers the function again.
Best way to do that would be in lifecycle methods or maintain the uses in the App and make UserList a dumb component by always passing the list of filtered users for it to display.
I'm trying to call a function from application startup. The function reads data from JSON via dataVar (set elsewhere) and tries to load it into {items} for further consumption:
const dataVar = JSONStuff;
class Global extends Component {
constructor(props) {
super(props);
this.state = {
query: '',
items: []
}
this.init();
}
// componentDidMount() {
// This doesn't work either!
// this.init();
// }
init() {
let { items } = dataVar;
this.setState({items});
}
render() {
return (
<div className="Global">
<Gallery items={this.state.items}/>
</div>
)
}
}
Then in Gallery.js:
import React, { Component } from 'react';
class Gallery extends Component {
render() {
return (
<div>
<h3>gallery:</h3>
{
this.props.items.map((item, index) => {
let {title} = item.name;
return (
<div key={index}>{title}</div>
)
})
}
</div>
)
}
}
export default Gallery;
Not sure why Global can't call a function inside of itself. I've tried with and without "this." I either get error to where the app won't complile or I get:
"Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op."
First of all, it's a warning, you probably better not call setState in componentDidMount.
My suggestion 1: assign value to state in constructor
constructor(props) {
super(props);
this.state = {
query: '',
items: dataVar.items,
};
}
Suggestion 2:
Do inside the componentWillReceiveProps
componentWillReceiveProps(nextProps) {
const { dataVar: items } = nextProps; // pass dataVar as props
this.setState({
items,
});
}
Plus try to debug your props and pay attention on your console for errors.
import React, { Component } from "react";
import FormUpdate from "../components/formUpdate";
import { fetchClothingItem, updateClothingItem } from "../actions/crud";
export default class Update extends Component {
constructor(props) {
super(props);
this.state = {
updateClothingItem: {}
};
}
componentWillMount() {
fetchClothingItem(this.props.match.params.postId)
.then(data => {
this.setState(state => {
state.updateClothingItem = data;
return state;
});
console.log("data", data);
//HERE IT IS RETURNING EXPECTED DATA
console.log("this.state.updateClothingItem",this.state.updateClothingItem)
})
.catch(err => {
console.error("err", err);
});
}
handleSubmit(data) {
//HERE IT IS THROWING:
> "TypeError: Cannot read property 'state' of undefined"
console.log("this.state.updateClothingItem", this.state.updateClothingItem);
updateClothingItem(this.state.updateClothingItem.id, data); this.props.router.push("/update");
}
render() {
return (
<div>
<FormUpdate
//onSubmit={this.handleSubmit.bind(this)}
id={this.state.updateClothingItem.id}
name={this.state.updateClothingItem.name}
sleeveLength={this.state.updateClothingItem.sleeveLength}
fabricWeight={this.state.updateClothingItem.fabricWeight}
mood={this.state.updateClothingItem.body}
color={this.state.updateClothingItem.color}
/>
<button
type="submit"
onClick={this.handleSubmit}
className="addItemButton"
>
Button
</button>
</div>
);
}
}
There are a few things that are technically wrong in terms of React code implementation.
Firstly, With ES6 style of writing a class, any function that needs to access the Class properties need to be explicitly binded. In your case you need to bind the handleSubmit function using arrow function of or binding in constructor.
See this answer for more details: Why and when do we need to bind functions and eventHandlers in React?
Secondly: You have your async request set up in the componentWillMount function and in the success response of it, you are setting state. However using setState in componentWillMount is triggered after the component is rendered so you still need to have an undefined check. You should instead make use of componentDidMount lifecycle function for async requests.
Check this answer on whether to have AJAX request in componentDidMount or componentWillMount
Third: setState is asynchronous and hence logging the state values after the setState function won't result in the correct output being displayed. Use the setState callback instead.
See these answers for more details:
calling setState doesn't mutate state immediately
When to use React setState callback
Code:
export default class Update extends Component {
constructor(props) {
super(props);
this.state = {
updateClothingItem: {}
};
}
componentDidMount() {
fetchClothingItem(this.props.match.params.postId)
.then(data => {
this.setState(state => {
state.updateClothingItem = data;
return state;
});
console.log("data", data);
//HERE IT IS RETURNING EXPECTED DATA
console.log("this.state.updateClothingItem",this.state.updateClothingItem)
}) // this statement will not show you correct result since setState is async
.catch(err => {
console.error("err", err);
});
}
handleSubmit = (data) => { . // binding using arrow function here
console.log("this.state.updateClothingItem", this.state.updateClothingItem);
updateClothingItem(this.state.updateClothingItem.id, data); this.props.router.push("/update");
}
render() {
return (
<div>
<FormUpdate
//onSubmit={this.handleSubmit.bind(this)}
id={this.state.updateClothingItem.id}
name={this.state.updateClothingItem.name}
sleeveLength={this.state.updateClothingItem.sleeveLength}
fabricWeight={this.state.updateClothingItem.fabricWeight}
mood={this.state.updateClothingItem.body}
color={this.state.updateClothingItem.color}
/>
<button
type="submit"
onClick={this.handleSubmit}
className="addItemButton"
>
Button
</button>
</div>
);
}
}
You forgot to bind your handleSubmit function to the class. You can either use arrow function to define the function.
handleSubmit=(data) =>{
...
}
Or you can bind the function in your constructor.
constructor(props) {
super(props);
this.state = {
updateClothingItem: {}
};
this.handleSubmit= this.handleSubmit.bind(this,data);
}
there is no state in constructor yet
if you want to set state in constructor you can do it like this
class SomeComponent extends Component {
constructor(props){
super(props)
this.state = { someKey: someValue }
}
}
or even like this
class SomeComponent extends Component {
state = { someKey: someValue }
}
but in this case babel should be properly configured