Home > Back-end >  I need to change the code from class component to function component in react
I need to change the code from class component to function component in react

Time:01-06

I want to convertc/change the code below from class to react function component. i want to convert state and component to react hooks. But i dont know to use function class properly, if any1 wanna give some example how to do it correctly.

A little example is enough, example for handle data, handle data post and how to change componentdidmount to useeffect. Thank you.

const BASE_URL = "https://dummyapi.io/data/v1";
const key = '618479acc2ef5ba8018516ac'

class Detail extends Component {
    state = {
        data: [],
        id: "",
        dataPost: [],  
    };

    handleData = (X) => {
        axios
            .get(`${BASE_URL}/user/${X}`, { headers: { "app-id": key } })
            .then((res) => {
                this.setState({ data: res.data });
                console.log(res.data);
            })
            .catch(console.error);
    };

    handleDataPost = (X) => {
        axios
            .get(`${BASE_URL}/user/${X}/post`, { headers: { "app-id": key } })
            .then((res) => {
                this.setState({ dataPost: res.data.data });
            })
            .catch(console.error);
    };

    componentDidMount() {
        this.handleData(this.props.match.params.id);
        this.handleDataPost(this.props.match.params.id);
        console.log(this.props);
    
    }

    render() {
        return (
            <div>
                <h4 style={{marginTop: '150px'}}>{this.state.data.firstName   " "   this.state.data.lastName}</h4>
                <h4>{this.state.data.email}</h4>
            </div>
        );
    }
}


export default Detail;

i tried to change it, here's how its look. i dont know what to do for the handleData, handleDataPost, and how to use useEffect. Anyone can show the example ? i wanna solve this.

function Detail () {

    const [data, setData] = useState([]); 
    const [id, setID] = useState("");
    const [dataPost, setDataPost] = useState([]);  

    const handeData = (X) => {
        axios.get(`${BASE_URL}/user/${X}`, { headers: { "app-id": key } })
        .then(res => {
            setData(res.data.data)
            console.log(res)
        })
        .catch(err =>{
            console.log(err)
        })
    }
}

export default Detail;

CodePudding user response:

I change your class commponent to a hook :

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

const BASE_URL = 'https://dummyapi.io/data/v1';
const key = '618479acc2ef5ba8018516ac';

export const Detail = (prosp) => {
  const { id } = useParams();
  const [data, setData] = useState();
  const [id, setId] = useState();
  const [dataPost, setDataPost] = useState();

  const handleData = (X) => {
    axios
      .get(`${BASE_URL}/user/${X}`, { headers: { 'app-id': key } })
      .then((res) => {
        setData(res.data);
        console.log(res.data);
      })
      .catch(console.error);
  };

  const handleDataPost = (X) => {
    axios
      .get(`${BASE_URL}/user/${X}/post`, { headers: { 'app-id': key } })
      .then((res) => {
        setDataPost(res.data.data);
      })
      .catch(console.error);
  };

  useEffect(() => {
    handleData(id);
    handleDataPost(id);
    console.log(props);
  }, []);
  return <div></div>;
};

in this case useEffect will call only once and if u want call it again when your props change you can add your dependency on it like this:


  useEffect(() => {
    handleData(id);
    handleDataPost(id);
    console.log(props);
  }, [variable]);

  •  Tags:  
  • Related