I have an array of servers and an AddServer button. I keep an array of servers as state, but when I add a server it immediately gets deleted. Anyone have any idea how to solve it?
Here is a video which demonstrates the problem: https://www.youtube.com/watch?v=ajS4_WQ4mn8
Here is part of the code I'm using:
import { SERVERS } from '../shared/servers';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
servers: SERVERS,
selectedServer: null
}
this.handleToggle = this.ToggleServer.bind(this);
this.HandleAddServer = this.HandleAddServer.bind(this);
}
HandleAddServer = (servername , serverip, servertype) => {
const serverslist = [...this.state.servers];
const newid = serverslist[serverslist.length -1].id 1;
serverslist.push({
ip: serverip,
id: newid,
servername: servername,
Type: servertype,
IsRunning: false
});
this.setState({ servers: serverslist });
}
Thanks for all the help
CodePudding user response:
It looks like you have a mutation issue, but instead of mutating your state you are mutating some external array which your state is holding a reference to, which indirectly mutates the state.
Don't mutate state!
Create a new array reference for the servers
state.
HandleAddServer = (servername , serverip, servertype) => {
const newid = this.state.servers[this.state.servers.length -1].id 1;
this.setState({
servers: [
...this.state.servers,
{
ip: serverip,
id: newid,
servername: servername,
Type: servertype,
IsRunning: false
},
],
});
}
CodePudding user response:
Solved it, and no wonder it was hard to catch.... I used a reactstrap button inside a form tag, and if you use a button in form using the usual on submit it causes a page to refresh. It's written here: https://github.com/react-bootstrap/react-bootstrap/issues/1510
The solution to fix it is to use the onClick attribute inside the form button and delete the onsubmit.