I'm trying to replace an initially empty array with an array made by a function using setState in React. I have in my constructor as follows:
this.state = {
sources: []
};
This displays the correct array (I tested it with [0,1,2]). However, when I try to setState in a method like so:
this.setState({
sources: [0,1,2]
})
it does not work and still displays the empty (or original) array. I understand you cannot mutate an array as state directly in React, but I don't think that's what I'm doing here. Here are some other things I have tried when researching this question, none of which have worked:
this.setState({
sources: [...this.state.sources, 1]
})
...
this.setState({
sources: this.state.sources.concat('test')
})
...
var temp = [0,1,2]
this.setState({
sources: temp
})
Thanks in advance for any help!
EDIT Full code:
export class SrcMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
sources: [],
};
this.searchSources = this.searchSources.bind(this);
}
searchSources() {
// commented out the actual method to replace with test code
var temp=[0,1,2];
console.log(temp); // [0,1,2] so I know the method works
this.setState({
sources: temp // etc for the other things i tried
})
console.log("this.state.sources: " + this.state.sources); // empty
}
render() {
return(
// etc...
<button type="button" onClick={this.searchSources}>Test</button>
);
}
}