I have a very basic question I have an array of JSONs and I could easily coopy them in functional component using
const [elements, setElements] = useState([]);
useEffect(() => {
const res = async () => {
const result = await axios.get('/data');
const data = result.data;
setElements(elements => [...elements, ...data]);
};
res();
}, []);
I want to convert them into class based components and when I try to copy in setState I get []. Code is below
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import Element from './components/Element';
class App extends Component {
constructor(props) {
super(props);
this.state = { elements: [] };
}
componentDidMount() {
const res = async () => {
const result = await axios.get('/data');
const data = result.data;
console.log(data);
this.setState({ elements: data });
};
res();
}
render() {
console.log(this.state.elements);
return (
<div className='wrapper'>
<div id='table'>
{this.state.elements.map(element => (
<Element elements={element} key={element._id} />
))}
</div>
</div>
);
}
}
export default App;
Here is a JSON which I am getting
(119) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]