Hello when I console log the state of my component anywhere outside the componentDidMount method I get that my state is full of empty arrays when they should have been built. I am grabbing the data from a JSON file and inside the componentDidMount I can see that the state changes to arrays with data, however anywhere else such as in my render, the state is back to its initial state.
I imagine this problem has to do with the component's lifecycle so would love to understand what is going on.
Many thanks!
import React from 'react';
import * as metrics from './metrics.json';
class MetricsTable extends React.Component {
state = {
coverages: [],
speeds: [],
qualities: [],
responsiveness: [],
securities: []
}
componentDidMount() {
metrics[0].map((metric) => {
if (metric.level_1 === 'Coverage') {
let joined = this.state.coverages.splice(0, 0, metric)
this.setState({ coverages: [...joined] })
}
if (metric.level_1 === 'Speed') {
let joined = this.state.speeds.splice(0, 0, metric)
this.setState({ speeds: [...joined] })
}
if (metric.level_1 === 'Quality') {
let joined = this.state.qualities.splice(0, 0, metric)
this.setState({ qualities: [...joined] })
}
if (metric.level_1 === 'Responsiveness') {
let joined = this.state.responsiveness.splice(0, 0, metric)
this.setState({ responsiveness: [...joined] })
}
if (metric.level_1 === 'Security') {
let joined = this.state.securities.splice(0, 0, metric)
this.setState({ securities: [...joined] })
}
})
}
render() {
// when I console log on this line I get empty arrays for my state
return (
<div>
// this following line displays my state with empty arrays
<pre>{JSON.stringify(this.state)}</pre>
hello
</div>
);
}
}
export default MetricsTable;
The fist picture shows state that has arrays with data, this one is console logged inside componentDidMount.
The second picture is the console log of this.state in my render function