vinayak shahdeo
vinayak shahdeo

Reputation: 1488

Conversion of functional components in react into class based component

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) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]   

Upvotes: 2

Views: 86

Answers (2)

Nathan
Nathan

Reputation: 8141

The issue is with how you're trying to set state on your React component, maybe you could try something like the following:

this.setState({ elements: data});

Can you try updating your componentDidMount() to the following:

async componentDidMount() {
 const {data} = await Axios.get('/data');
 this.setState({ elements: data });
}

Hopefully that helps!

Upvotes: 2

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

to make code equal it should be written as this

this.setState(state => ({
   elements: [...state.elements, ...data]
}));

Upvotes: 1

Related Questions