Reputation: 183
import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
projectList: [],
myProjects: [],
userList: [],
};
this.createProject = this.createProject.bind(this);
}
createProject(title, desc, langs, len, exp) {
this.setState({
projectList: this.state.projectList.push(
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
)
});
}
deleteProject(title) {
const projects = this.state.projectList.filter(
p => p.title !== title
);
this.setState({projects});
}
render() {
return(
<div>
<Form createProject = {this.createProject} />
{this.state.projectList.map((params) =>
<Project {...params}/>)}
</div>
);
}
}
export default App;
Hello, when running this, createProject gets passed as a prop to another class, which calls createProject with certain parameters. However, upon trying to render, it returns this error. TypeError: this.state.projectList.map is not a function. Any advice on how to fix it?
Upvotes: 1
Views: 1020
Reputation: 13
Hi Adam,
For the current problem below snippet would solve this issue
this.setState({
projectList: [...this.state.projectList,
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
]
});
For better understanding refer below link:
https://www.robinwieruch.de/react-state-array-add-update-remove
Upvotes: 0
Reputation: 743
You cannot declare state like this, you can do something like:
this.setState({
projectList: [...this.state.projectList, (
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
)]
});
Upvotes: 0
Reputation: 1073968
push
returns the new length of the array, it doesn't return the array. So this code is replacing the array with a number:
this.setState({
projectList: this.state.projectList.push( // <============
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
)
});
Numbers don't have a map
method. :-)
You probably wanted to do this, which creates a new array with the new item added to it:
this.setState({
projectList: [...this.state.projectList, {
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}]
});
Upvotes: 3