luiisca / Budgetist

budgetist.vercel.app
1 stars 0 forks source link

migrate simulation page to RSC #19

Closed luiisca closed 6 months ago

luiisca commented 6 months ago

Just finished replacing useSimData with a <BalanceProvider /> level useEffect that also syncs BalanceReducer with trpc data to simplify the balanceContext api, basically we do not longer provide trpc data through <BalanceProvider />.

        useEffect(() => {
            // Sync trcp responses with global simulation reducer, 
            // so calls to SIM_RUN always have access to the latest db data
            // It also defines a mechanism to rerun SIM_RUN every time some of it's dependencies gets updated,
            // like when a new salary or category record is added, this reduces the need for calling this action from mutation.onSucess
            const apiResArr = ['categories', 'salaries', 'user'] as const
            const apiRes = {
                categories: categoriesApiRes,
                salaries: salariesApiRes,
                user: userApiRes
            }
            for (const val of apiResArr) {
                const dataUpdatedAt = apiRes[val].dataUpdatedAt
                const prevDataUpdateAt = apiResUpdateAtTimes.current[val]

                if (dataUpdatedAt > prevDataUpdateAt) {
                    // data was revalidated, either manually through query.invalidate or react query fresh time run out
                    apiResUpdateAtTimes.current[val] = dataUpdatedAt
                    if (apiRes[val].data) {
                        dispatch({
                            type: "UPDATE_TRPC_DATA",
                            payload: {
                                [val]: apiRes[val].data
                            }
                        })
                    }

                    // totalBalance outdated time to rerun simulation
                    // this is primarily used as a replacement for calling SIM_RUN action on every mutation.onSucess call
                    if (apiRes.categories.data && apiRes.salaries.data && apiRes.user.data) {
                        if (apiRes.categories.data.length > 0 && apiRes.salaries.data.length > 0 && apiRes.user.data) {
                            dispatch({ type: "SIM_RUN", years: state.years })
                        }
                    }
                    // remove loading state that might've started on some onFormSubmit trpc onMutate cb
                    dispatch({ type: "TOTAL_BAL_LOADING", totalBalanceLoading: false })
                }
            }
        }, [categoriesApiRes, salariesApiRes, userApiRes])
luiisca commented 6 months ago

removed it entirely to reduce unnecessary calls to SIM_RUN and api endpoints. Instead called SIM_RUN manually after creating and removing records.