I have an array as such:
product = [
{
name: " size one",
price: 1
},
{
name: "size two",
price: 2
},
,
{
name: "size three",
price: 3
}
];
I had previously separated odd and even array indexes like this:
for (let i=0; i< product.length; i++ ) {
if (i % 2 === 0 ){
evenArray.push(product[i])
} else {
oddArray.push(product[i])
}
};
But I would like to move this to the constructor and out of render.
I have it written like this in a componenetDidMount()
:
for (let i=0; i< this.state.product.length; i++ ) {
if (i % 2 === 0 ){
this.setState({
evenArray: [...this.state.evenArray, this.state.product[i]]
});
} else {
this.setState({
oddArray: [...this.state.oddArray, this.state.product[i]]
});
}
};
But it doesn't work. I'm familiar with the idea that you cannot change the state directly but update it only which is why .push() can't be used but how come the above does not work?
-----EDIT OF REAL CODE-----
componentDidMount() {
const oauth = OAuth({
consumer: {
key: 'XXXXXXXXX',
secret: 'XXXXXXXXXXX',
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return crypto.createHmac('sha1', key).update(base_string).digest('base64');
}
});
const request_data1 = {
url: 'http://localhost:8888/wp-json/wc/v2/products/28/variations?per_page=15',
method: 'GET',
};
const request_data2 = {
url: 'http://localhost:8888/wp-json/wc/v2/products/28/',
method: 'GET',
};
fetch(request_data1.url, {
method: request_data1.method,
headers: oauth.toHeader(oauth.authorize(request_data1))
})
.then(response => response.json())
.then(response => {
this.setState({
products1: response.reverse()
})
})
fetch(request_data2.url, {
method: request_data2.method,
headers: oauth.toHeader(oauth.authorize(request_data2))
})
.then(response => response.json())
.then(response => {
this.setState({
products2: response
})
})
const evenArray = [];
const oddArray = [];
for (let i = 0; i < this.state.products1.length; i++) {
if (i % 2 === 0) {
evenArray.push( this.state.products1[i] );
} else {
oddArray.push(this.state.products1[i]);
}
};
this.setState( prevState => ({
evenArray: [ ...prevState.evenArray, ...evenArray ],
oddArray: [...prevState.oddArray, ...oddArray],
}));
}