I'm new to React, so I'm struggling with this:
why does setting state as a single object array works, but getting the array from state, pushing to it, and setting as state again doesn't work?
This is the working code. I have this IMAGE array in as state, not initialized:
class PersonalBananas extends React.Component {
constructor(){
super();
this.state = {
username: 0,
images: 0,
pred: 0,
IMAGES: 0
}
this.imgList = this.imgList.bind(this)
}
In componentDidMount I call the imgList():
componentDidMount() {
let $this = this;
axios.get('http://localhost:8081/auth/username')
.then((response) => {
let uname = response.data;
this.setState({
username: uname
});
})
axios.get('http://localhost:8081/auth/files')
.then((response) => {
let imgs = response.data;
console.log("images response: "+imgs);
this.setState({
images: imgs
},
function() { $this.imgList() }
);
})
}
Inside imgList() I call getImgPred:
imgList = () => {
var $this = this;
const IMAGES = [];
const imgpaths = this.state.images;
console.log("images from imgLis():"+imgpaths);
for (let i = 0; i < imgpaths.length; i++) {
var path = imgpaths[i]
this.getImgPred(path);
console.log("pred:"+$this.state.pred);
}
console.log("IMAGES from imgLis():"+IMAGES);
};
And here finally I call the IMAGESpush():
getImgPred = (path) => {
var username = this.state.username;
var $this = this;
let regex = new RegExp(username+'\/(.*?)$');
let imgRegex= /{username}\/(.*?)$/;
let filename = regex.exec(path);
console.log("filename at front:"+filename[1]);
console.log("regex1:"+imgRegex+", regex2:"+regex);
axios.post('http://localhost:8081/auth/imgpred',
"filename=" + filename[1]
).then(function (response) {
console.log("response at front (get img prediction):"+response.data);
if (response.status === 200) {
$this.setState({
pred: response.data
}, function() { $this.IMAGESpush(path) } );
}
});
}
Here is the problem: when I just initialize the const IMAGES = [], push to it, then set state - it works fine. What i'm trying to do is: const Images = this.state.IMAGES. I can't do it.
IMAGESpush = (path) => {
var $this = this;
const IMAGES = [];
IMAGES.push({
src: process.env.PUBLIC_URL +`/${path}`,
thumbnail: process.env.PUBLIC_URL +`/${path}`,
thumbnailWidth: 320,
thumbnailHeight: 320,
caption: $this.state.pred
})
this.setState({
IMAGES: IMAGES
})
}
render() {
return (
<div>
<Gallery images={this.state.IMAGES}/>
</div>
)
}
}
export default PersonalBananas;