Sorry, I really miss something with the transmission of state within props of sub components in React.
I have implemented a version of a todo list with 3 components.
There is a Form component and a ListTodo component. The state is stored only in the App component.
import React, {Component} from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
tasks: ["un truc", "autre truc"]
};
this.addTask = this.addTask.bind(this);
}
addTask(task) {
this.setState({
tasks: this.state.tasks.push(task)
})
}
render() {
return (
<div className="App">
<Form onTaskAdded={ this.addTask }></Form>
<ListTodo tasks={ this.state.tasks }></ListTodo>
</div>
);
}
}
class Form extends Component {
constructor(props) {
super(props);
this.state = {
task: ""
}
this.handleChange = this.handleChange.bind(this);
this.addTask = this.addTask.bind(this);
}
handleChange(event) {
this.setState({
task: event.target.value
});
}
addTask(event) {
this.props.onTaskAdded(this.state.task);
event.preventDefault();
}
render() {
return (
<form onSubmit={ this.addTask }>
<input placeholder="À faire" onChange={ this.handleChange }></input>
<input type="submit"></input>
</form>
)
}
}
class ListTodo extends Component {
render() {
const tasks = this.props.tasks.map((t, i) => (
<li key={i}>{t}</li>
))
return (
<ul>{tasks}</ul>
)
}
}
export default App;
The display is good at start so the ListTodo achieves to see the prop tasks. But after a form submission, I get an error on ListTodo.render :
TypeError: this.props.tasks.map is not a function
When I console.log the this.props.tasks, I don't get my array but the length of the array.
Do you know why?
Edit :
Thanks for answers guys, you're right. I missed the behavior of Array.push.
But React seems still odd. If I let the mistaken code
this.setState({
tasks: this.state.tasks.push(task)
})
then a console.log(JSON.stringify(this.state)) displays :
{"tasks":["un truc","autre truc","aze"]}.
Very disturbing to not be able to trust a console.log...
As per MDN DOC:
The push() method adds one or more elements to the end of an array and
returns the new length of the array.
Array.push never returns the result array, it returns the number, so after adding the first task, this.state.tasks becomes a number, and it is throwing the error when you trying to run map on number.
You did the mistake here:
addTask(task) {
this.setState({
tasks: this.state.tasks.push(task)
})
}
Write it like this:
addTask(task) {
this.setState( prevState => ({
tasks: [...prevState.tasks, task]
}))
}
Another import thing here is, the new state will be depend on the previous state value, so instead of using this.state inside setState, use updater function.
Explanation about Edit part:
Two important things are happening there:
1- setState is async so just after setState we can expect the updated state value.
Check this for more details about async behaviour of setState.
2- Array.push always mutate the original array by pushing the item into that, so you are directly mutating the state value by this.state.tasks.push().
Check the DOC for more details about setState.
Check the MDN Doc for spread operator (...).
Check this snippet:
let a = [1,2,3,4];
let b = a.push(5); //it will be a number
console.log('a = ', a);
console.log('b = ', b);
The problem is in how you add a task in the App’s state.
addTask(task) {
this.setState({
tasks: this.state.tasks.push(task)
})
}
See, Array.prototype.push returns the length of the array after adding an element. What you really want is probably Array.prototype.concat.
addTask(task) {
this.setState({
tasks: this.state.tasks.concat([ task ])
})
}
Also, thanks to #t-j-crowder pointers and as also reported by #mayank-shukla, you should use a different approach to mutate your state:
addTask(task) {
this.setState(function (state) {
return {
tasks: state.tasks.concat([ task ])
}
});
}
Or using ES2015 Arrows, Object destructuring and Array spread:
addTask(task) {
this.setState(({ tasks }) => ({
tasks: [ ...tasks, task ]
}));
}
Since Component.prototype.setState can be asynchronous, passing a function to it will guarantee the new state values depend on the right, current previous values.
This means that if two or more setState calls happen one after another you are this way sure that the result of the first one will be kept by applying the second.
As the other answers stated, the Array push method does not return the array. Just to complement the answers above, if you are using ES6, a nice and elegant way of doing this is using the spread operator (you can read more about it here)
this.setState({
tasks: [...this.state.tasks, task]
})
It is essentially the same as using the concat method, but I think this has a nicer readability.
The problem is from Array.push return the number of elements in the array and not the updated array
addTask(task) {
this.setState({
tasks: this.state.tasks.push(task)
})
}
To fix this you can push to state.tasks then setState with it later on:
addTask(task) {
this.state.tasks.push(task);
this.setState({
tasks: this.state.tasks
})
}
This way you set state.task to the updated array.
Related
Updated code
Initialized constructor and placed filter and loadOptions in class render method.
Still showing error saying that this.state.cars.filter is not a function.
import React, { Component } from 'react';
import AsyncSelect from 'react-select/async';
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: null,
cars: []
};
}
componentDidMount() {
fetch(url)
.then(res => {
this.setState(prevState => ({...prevState, cars: res}))
})
}
handleInputChange = (newValue) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
};
render() {
const filterCars = (inputValue) => {
return this.state.cars.filter((i) =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
};
const loadOptions = (
inputValue,
callback) => {
setTimeout(() => {
callback(filterCars(inputValue));
}, 1000);
};
return (
<div>
<AsyncSelect
cacheOptions
loadOptions={loadOptions}
defaultOptions
onInputChange={this.handleInputChange}
/>
</div>
);
}
}
Example code of json file that Im fetching data from
[{"make":"KIA","link":"\/images\/image.jpg"},{"make":"BMW","link":"\/images\/image.jpg"}]
There are a couple of issues here. First is that you should declare state inside of a constructor, so instead of declaring state like that, do the following:
constructor(props) {
super(props)
this.state = {inputValue: '', cars: []}
}
Then you need to deal with your state mutations. Whenever you call setState, you are essentially giving it a new object which it sets the state to. You do not reassign the properties, you return a new object.
To resolve this reassignment issue, ES6 has introduced the spread operator which was not specifically designed to deal with mutations but it helps a lot.
Essentially, whenever you want to create a copy of an object, you don't do
let a = b
instead you do
let a = {...b}
With this change, changes on A will not reflect on B. So you make a copy instead of a duplicate.
How you can use this to avoid state mutation?
Whenever you call setState, make sure to first spread the rest of the state accross the new one before making any property changes:
setState(prevState => ({...prevState, cars: res}))
This way, you do not essentially remove the inputValue from your state object which can cause undefined issues.
Back to the main issue, your function filterCars is located outside of your class and in there you are trying to access this.state. Move the filterCars function inside of the class and your error will be resolved but if you don't resolve the mutation issues, it will not work as expected.
I'm trying to update an array inside of my component's state from within a .map() method being run inside the render() method. There are currently 9 objects within the array I'm mapping that I wish to extract a property from and add to the array inside the state. When console.log()ing the state to see why my page was freezing for so long I saw that it was iterating 1,000 copies of each entry.
Here's an example of one of the nine objects I'm iterating over
{
"name": "Trap_808",
"key" : "Q",
"path": "https://firebasestorage.googleapis.com/v0/b/online-coding.appspot.com/o/drum%20samples%2Ftrap-808-08.wav?alt=media&token=c3c63635-45b0-4c99-82ff-e397f1153fa0"
}
Here's how I have my state defined inside the constructor.
this.state = { currentSound: '', triggerKeys: [] };
What I'm trying to do is add the key property from the object to the triggerKeys property as the objects are iterated over. This is how I'm rendering the nine objects with the .map() method.
<ul id="pad-shell">
{
DRUM_PATCH.map( sound =>{
this.setState({ triggerKeys: [...this.state.triggerKeys, sound.key] });
console.log(this.state);
return <DrumButton
name={sound.name}
soundKey={sound.key}
sourceLink={sound.path}
trigger={this.updateSound}
/>
});
}
</ul>
I also tried updating the state like this
this.setState( prevState =>{ return { triggerKeys: [...prevState.triggerKeys, sound.key] } });
The above example is actually the one that returns 9,000 entries, the code above it returns 1,000 of the same entry. Aside from this everything else is working as expected so I don't think there's anything else going on elsewhere in my code. Can anyone spot what the problem is? If you need more code let me know.
As others have said, you should not use this.setState inside of render - doing so will most likely cause an infinite update loop.
You haven't provided enough code context to give you a definitive answer but
if DRUM_PATCH comes from props
class Component extends React.Component {
constructor (props) {
super(props)
this.state = { triggerKeys: props.drumPatch.map(s => s.key) }
}
render() {
...
}
}
if DRUM_PATCH is just a constant
this.state = { triggerKeys: props.drumPatch.map(s => s.key) }
becomes
this.state = { triggerKeys: DRUM_PATCH.map(s => s.key) }
hey i guesss you are doing it in render function , if yes then everytime it changes the state, it will rerender and change the state again , it will be an infinite loop.
this.setState({ triggerKeys: [...this.state.triggerKeys, sound.key] });
this is the culprit
Can someone help me solve how do I setState inside componentDidUpdate and not have an infinite loop? Some suggestions said to have a conditional statement, but I am not too familiar with how do I set the conditional for my code.
This is what my code looks like:
I have a dashboard component that gets all the companies and projects data from external functions where the fetch happens and then updates the state. The projects are associated with the company's id.
I am able to get the list of all the projects in JSON, but I can't figure out how to update my projects state inside componentDidUpdate once rendered.
CompanyDashboard.js
import { getCompanys } from "../../actions/companyActions";
import { getProjects } from "../../actions/projectActions";
class CompanyDashboard extends Component {
constructor(props) {
super(props);
this.state = {
companies: [],
projects: []
};
}
componentWillMount() {
// get all companies and update state
getCompanys().then(companies => this.setState({ companies }));
}
componentDidUpdate(prevState) {
this.setState({ projects: this.state.projects });
}
render() {
const { companies, projects } = this.state;
{
companies.map(company => {
// get all the projects
return getProjects(company);
});
}
return <div />;
}
}
export default CompanyDashboard;
companyActions.js
import { getUser, getUserToken } from './cognitoActions';
import config from '../../config';
export function getCompanys() {
let url = config.base_url + '/companys';
return fetch(url, {
method: 'GET',
headers: {'token': getUserToken() }
})
.then(res => res.json())
.then(data => { return data })
.catch(err => console.log(err));
}
projectActions.js
import { getUserToken } from './cognitoActions';
import config from '../../config';
export function getProjects(company) {
let url = config.base_url + `/companys/${company._id['$oid']}/projects`;
return fetch(url, {
method: 'GET',
headers: {'token': getUserToken() }
})
.then(res => res.json())
.then(data => { return data })
.catch(err => console.log(err));
}
The following code is not doing anything meaningful. You are setting your state.projects to be equal to your state.projects.
componentDidUpdate() {
this.setState({ projects: this.state.projects })
}
Also, the following code is not doing anything meaningful because you are not saving the result of companies.map anywhere.
{
companies.map((company) => {
return getProjects(company)
})
}
It's hard to tell what you think your code is doing, but my guess is that you think that simply calling "companies.map(....) " inside your render function is going to TRIGGER the componentDidUpdate function. That is not how render works, you should go back to the drawing board on that one. It also looks like you think that using the curly brackets {} inside your render function will display the objects inside your curly brackets. That's also not true, you need to use those curly brackets inside the components. For instance: {projects}
If I had to guess... the following code is how you actually want to write your component
import { getCompanys } from '../../actions/companyActions';
import { getProjects } from '../../actions/projectActions';
class CompanyDashboard extends Component {
constructor(props) {
super(props);
this.state = {
companies: [],
projects: []
}
}
componentWillMount() {
getCompanys().then(companies => {
const projectPromises = companies.map((company) => {
return getProjects(company)
});
Promise.all(projectPromises).then(projects => {
//possibly a flatten operator on projects would go here.
this.setState({ companies, projects });
});
/*
* Alternatively, you could update the state after each project call is returned, and you wouldn't need Promise.all, sometimes redux can be weird about array mutation in the state, so look into forceUpdate if it isn't rerendering with this approach:
* const projectPromises = companies.map((company) => {
* return getProjects(company).then(project => this.setState({projects: this.state.projects.concat(project)}));
* });
*/
)
}
render() {
const { companies, projects } = this.state;
//Not sure how you want to display companies and projects, but you would
// build the display components, below.
return(
<div>
{projects}
</div>
)
}
}
export default CompanyDashboard;
componentDidUpdate has this signature, componentDidUpdate(prevProps, prevState, snapshot)
This means that every time the method gets called you have access to your prevState which you can use to compare to the new data, and then based on that decide if you should update again. As an example it can look something like this.
componentDidUpdate(prevProps, prevState) {
if (!prevState.length){
this.setState({ projects: this.state.projects })
}
}
Of course this is only an example since I don't know your requirements, but this should give you an idea.
When componentDidUpdate() is 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.
`componentDidUpdate(prevProps) {
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}`
You must check the state/props if new state/props different from previous one then you can allow to update your component.
You may call setState() immediately in componentDidUpdate() but
note that it must be wrapped in a condition like in the example above,
or you’ll cause an infinite loop. It would also cause an extra
re-rendering which, while not visible to the user, can affect the
component performance. If you’re trying to “mirror” some state to a
prop coming from above, consider using the prop directly instead.
This is because componentDidUpdate is called just after a component takes up somechanges in the state. so when you change state in that method only then it will move to and from from that method and state change process
I am unable to get props inside constructor that I have implemented using redux concept.
Code for container component
class UpdateItem extends Component{
constructor(props) {
super(props);
console.log(this.props.item.itemTitle) // output: undefined
this.state = {
itemTitle: this.props.item.itemTitle,
errors: {}
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
//If the input fields were directly within this
//this component, we could use this.refs.[FIELD].value
//Instead, we want to save the data for when the form is submitted
let state = {};
state[e.target.name] = e.target.value.trim();
this.setState(state);
}
handleSubmit(e) {
//we don't want the form to submit, so we pritem the default behavior
e.preventDefault();
let errors = {};
errors = this._validate();
if(Object.keys(errors).length != 0) {
this.setState({
errors: errors
});
return;
}
let itemData = new FormData();
itemData.append('itemTitle',this.state.itemTitle)
this.props.onSubmit(itemData);
}
componentDidMount(){
this.props.getItemByID();
}
componentWillReceiveProps(nextProps){
if (this.props.item.itemID != nextProps.item.itemID){
//Necessary to populate form when existing item is loaded directly.
this.props.getItemByID();
}
}
render(){
let {item} = this.props;
return(
<UpdateItemForm
itemTitle={this.state.itemTitle}
errors={this.state.errors}
/>
);
}
}
UpdateItem.propTypes = {
item: PropTypes.array.isRequired
};
function mapStateToProps(state, ownProps){
let item = {
itemTitle: ''
};
return {
item: state.itemReducer
};
}
function mapDispatchToProps (dispatch, ownProps) {
return {
getItemByID:()=>dispatch(loadItemByID(ownProps.params.id)),
onSubmit: (values) => dispatch(updateItem(values))
}
}
export default connect(mapStateToProps,mapDispatchToProps)(UpdateItem);
Inside render() method am able to get the props i.e. item from the redux but not inside constructor.
And code for the actions to see if the redux implementation correct or not,
export function loadItemByID(ID){
return function(dispatch){
return itemAPI.getItemByID(ID).then(item => {
dispatch(loadItemByIDSuccess(item));
}).catch(error => {
throw(error);
});
};
}
export function loadItemByIDSuccess(item){
return {type: types.LOAD_ITEM_BY_ID_SUCCESS, item}
}
Finally my reducer looks as follows,
export default function itemReducer(state = initialState.item, action) {
switch (action.type) {
case types.LOAD_ITEM_BY_ID_SUCCESS:
return Object.assign([], state = action.item, {
item: action.item
});
default:
return state;
}
}
I have googled to get answers with no luck, I don't know where i made a mistake. If some one point out for me it would be a great help. Thanks in advance.
The reason you can't access the props in the constructor is that it is only called once, before the component is first mounted.
The action to load the item is called in the componentWillMount function, which occurs after the constructor is called.
It appears like you are trying to set a default value in the mapStateToProps function but aren't using it at all
function mapStateToProps(state, ownProps){
// this is never used
let item = {
itemTitle: ''
};
return {
item: state.itemReducer
};
}
The next part I notice is that your are taking the state from redux and trying to inject it into the component's local state
this.state = {
itemTitle: this.props.item.itemTitle,
errors: {}
};
Mixing redux state and component state is very rarely a good idea and should try to be avoided. It can lead to inconsistency and and hard to find bugs.
In this case, I don't see any reason you can't replace all the uses of this.state.itemTitle with this.props.items.itemTitle and remove it completely from the component state.
Observations
There are some peculiar things about your code that make it very difficult for me to infer the intention behind the code.
Firstly the reducer
export default function itemReducer(state = initialState.item, action) {
switch (action.type) {
case types.LOAD_ITEM_BY_ID_SUCCESS:
return Object.assign([], state = action.item, {
item: action.item
});
default:
return state;
}
}
You haven't shown the initialState object, but generally it represents the whole initial state for the reducer, so using initialState.item stands out to me. You may be reusing a shared initial state object for all of the reducers so I'm not too concerned about this.
What is very confusing the Object.assign call. I'm not sure it the intention is to output an object replacing item in the state, or if it is to append action.item to an array, or to have an array with a single item as the resulting state. The state = action.item part is also particularly puzzling as to it's intention in the operation.
This is further confused by the PropTypes for UpdateItem which requires item to be an array
UpdateItem.propTypes = {
item: PropTypes.array.isRequired
};
But the usage in the component treats it like and object
this.state = {
// expected some kind of array lookup here |
// V---------------
itemTitle: this.props.item.itemTitle,
errors: {}
};
Update from comments
Here is a example of what I was talking about in the comments. It's a simplified version of your code (I don't have all your components. I've also modified a few things to match my personal style, but hopefully you can still see what's going on.
I'm trying to update my regular React state through Immutable, and got into some few issues. The state isn't deeply nested or it isn't nested from anything other than the state itself, such as { "username" : "keyval" : null}}
This means I could not do something such as username.update('keyval', something), instead I need another approach. Its a rather easy question, I just don't know how to do it. Here's how my setState looks like, which I want to make an Immutable setState action.
handleUpdatePassword(event) {
event.persist()
this.setState(({password}) => ({
password: state.update('password', event.target.value)
})
);
}
And here is the error I get when trying:
handleUpdatePassword(event) {
event.persist()
this.setState({
password: state.update('password', event.target.value)
})
}
Also, This works, but I get this error: this.state.updater is not a function
handleUpdateUsername(event) {
console.log(this.state)
event.persist()
this.setState({
username: this.state.update('username', event.target.value)
})
}
state should be a plain JavaScript object as you can read in the documentation.
Note that state must be a plain JS object, and not an Immutable
collection, because React's setState API expects an object literal and
will merge it (Object.assign) with the previous state.
Your initial state should look something like this
constructor(){
...
this.state = {data: Map({ password: "", username: ""})}
}
After that, you'll be able to update the data like this
handleUpdatePassword(event) {
this.setState(({data}) => ({
data: data.update('password', password => event.target.value)
}));
}
You are creating explicit objects. Just let ImmutableJS do it for you.
class YourReactComp extends React.Component {
constructor() {
this.state = Immutable.Map({"username": ""});
}
handleUpdateUsername(event) {
console.log(this.state)
event.persist()
this.setState(this.state.set("username", event.target.value));
}
}
EDIT
ImmutableMap.update(key, updater) uses a callback to set the value, you want ImmutableMap.set(key, newValue) here.