メインコンテンツへスキップ

【CodeLog Day.01】 UseEffectを減らす。

    awaitを使えば複数存在するuseEffectを1つにできる。
    awaitなしだと非同期関数の実行順はuseEffectの依存配列によって制御することになる。useEffectを複数配置してしまうのはこれが原因。
    awaitは非同期処理の完了まで次の処理を実行しないから、非同期関数を同期関数っぽく処理できるので、これを使えば1つのuseEffectの中で非同期関数に実行順を与えることができるようになる。

    // customer取得
    useEffect(() => {
      fetchCustomer(studioId, customerId).then(res => setCustomer(res.customer))
    }, [studioId, customerId])
    
    // customer変化に応じてタイトル設定
    useEffect(() => {
      if (customer) {
        setTitle(`${customer.nameLabel}さん`)
      }
    }, [customer])
    
    // 請求取得
    useEffect(() => {
      fetchCustomerMonthlyBills(studioId, customerId, month)
        .then(res => setBills(res.charges))
    }, [studioId, customerId, month])

    こういうのが

    useEffect(() => {
      const loadData = async () => {
        const resCustomer = await fetchCustomer(studioId, customerId)
        const customerData = resCustomer.customer
        if (!customerData) return
        setCustomer(customerData)
        setTitle(`${customerData.nameLabel}さん`)
    
        const resBills = await fetchCustomerMonthlyBills(studioId, customerId, month)
        setBills(resBills.charges)
      }
    
      loadData()
    }, [studioId, customerId, month])

    こうなる。

     
     
    より小さく、少なく、軽く。 をテーマにNoteを書いています。 API作るのが大好きです。

    あなたへのおすすめ