0

Please suggest to how to write the constructor in functional component using react js...as I'm planning to convert class component to functional component....could anyone help that

import React, { Component } from "react";
class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: []
    };
  }
  componentDidMount() {
    axios
      .get("https://www.example.com/users/id")
      .then(response => {
        this.setState({ descriptions: response.data });
        // console.log(response.data)
      })
      .catch(error => {
        console.log(error);
      });
  }
  render() {
    const { users } = this.state;
    return <div>Data</div>;
  }
}
export default Example;
keikai
  • 14,085
  • 9
  • 49
  • 68
Manu Panduu
  • 411
  • 1
  • 9
  • 17
  • 1
    You can't use constructor inside a function. You should look into React hooks like useState for initializing the state. – Ramesh Reddy Mar 12 '20 at 09:02
  • Functions do not have constructors. React functional components can typically use combinations of `useState` and `useEffect` hooks to initialize state. If you share your attempt at converting a class-based component to a functional component and are stuck we can help. – Drew Reese Mar 12 '20 at 09:02
  • There is no constructor in a function, constructors are used to create instances of *classes*. – Roberto Zvjerković Mar 12 '20 at 09:03
  • Thank you very much one and all for the answers – Manu Panduu Mar 12 '20 at 09:24

1 Answers1

-1

In order to use state, or lifecycle method in functional components you should use React Hooks

import React, { useState, useEffect } from 'react';

const Example =() => {
 const [users, setUsers] = useState([])
 useEffect(()=> {
    axios.get("https://www.example.com/users/id")
            .then(response => {
               // use setState hook here
                // console.log(response.data)
            })
            .catch(error => {
                console.log(error)
            })
 }, [])   

 return (
            <div>
              Data
            </div>
         )
}
export default Example
Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42