Prevent infinite api request in componentDidUpdate Method

ကျတော်တို့ နောက်တခုထပ်ပြီးတော့လေ့လာလိုက်ကြရအောင်ဗျ componentDidUpdate ရဲ့ method ထဲမှာ

Parameter ၂ ခုကိုလက်ခံပါတယ် တခုက previousProps နဲ့ နောက်တစ်ခုက တော့ previousState ဖြစ်ပါတယ်

အဲဒါကို ကျတော်တို့ တချက်လောက်လေ့လာလိုက်ကြရအောင် ပါ ဘာလို့အဲဒါကို

ကျတော်ရှင်းပြရတာလည်းဆိုတော့ သူက အရေးကြီးတာမလို့ပါ

ကျတော်တို့ ကုဒ်လေးတွေကို ဒီလိုလေးရေးလိုက်ပါမယ်

class LifeCycle extends Component {
    constructor(){
        super()
        console.log("constructor start")
        this.state = {
            count : 0,
            data : []
        }
    }
    getData = async() => {
        const data = await fetch("https://jsonplaceholder.typicode.com/users")
        const result = await data.json()
        console.log(result)
        this.setState({
            data : result
        })
    }
    componentDidMount(){
        console.log("component life cycle start")
    }
    componentDidUpdate(){
        this.getData()
        console.log("component state is update")
    }
    increment = () => {
        this.setState({
            count : this.state + 1
        }
    }
    render(){
    console.log("render start")
        return (
            <div>
                <h1>Count - {count}</h1>
                <button onClick={this.increment}> Increment </button>
                {this.state.data.map((item , index ) => (
                    <p key={index}>{item.name}</p>
                ))}
            </div>
        )
    }
}

ကျတော်တို့က ဒီတစ်ခါမှာ ကျတော်တို့က increment ဆိုတဲ့ button လေးကို click လုပ်တဲ့အချိန်မှာ

ကျတော်တိုက api လေးကို fetch လုပ်ပေးဖို့အတွက်ရေးလိုက်တာပါ

အဲလို fetch ပီးတော့ data ကို render လုပ်လိုက်မှာပါ အဲအချိန်မှာ ကျတော်တို့က button ကို

click လုပ်လိုက်တဲ့အချိန်မှာ ဘာဖြစ်သွားတာလည်းဆိုတော့ api request ကို infinite လုပ်နေတာကိုမြင်ရပါလိမ့်မယ်

အဲဒါကို ကျတော်တို့က သတိထားပေးရမှာပါ အဲလိုမျိုးအလုပ်လုပ်ချင်တဲ့အခါမှာသူ့ကို prevent လုပ်ဖို့

အတွက် ကျတော်တို့က previousState ကို ပြန်ယူပြီးတော့ ပြန်အလုပ်လုပ်စေခိုင်းရပါတယ်

အဲဒါကို ကျတော်တို့က ကုဒ်လေးကို ဒီလိုလေးပြင်ရေးလိုက်ပါမယ်

componentDidUpdate(prevProps, prevState){
        if(prevState.count !== this.state.count){
                this.getData()
        }
        console.log("component state is update")
    }

အဲလိုလေးရေးပြီးတော့ ကျတော်တို့က infinite api request ကို ကာကွယ်လို့ရပါတယ်

အဲလောက်ဆိုရင်တော့ ကျတော်တို့ componentDidUpdate method ကို နားလည်သွားမယ်လို့ မျှော်လင့်ပါ တယ်

နောက်ထပ်တစ်ခုကို ထပ်လေ့လာသွားကြရအောင်ပါ

Last updated