Search code examples
reactjsreact-hooksuse-statereact-functional-component

how can i use constructor in function component (fat arrow function)?


I want to use fat arrow function instead of this class component.

class Categories extends Component{
    
    state = {
        category : []
    }
    constructor() {
        super();
        this.getCategories();
    }
    getCategories = async () => {
        let data = await api.get('/').then(({data})=>data);
        this.setState({category:data})
    }
render() {
        return(
-----
);
}
export default Categories;

how can i use this in function component


Solution

  • import React, { useCallback, useEffect, useState } from 'react';
    import PropTypes from 'prop-types';
    
    export const Categories = ({ propA, propB }) => {
      const [category, setCategory] = useState([]);
    
      const getCategories = useCallback(async () => {
        let res = await api.get('/').then(({data})=>data);
        setCategory(res);
      }, [setCategory]);
    
      useEffect(() => {
        getCategories();
      }, []);
    
      return (
        <>
          <h1>{propA}</h1>
          <h1>{prop2}</h1>
          <h1>{category}</h1>
        </>      
      );
    };
    
    Categories.propTypes = {
      propA: PropTypes.string.isRequired,
      propB: PropTypes.bool,
    };