Skip to content

Commit

Permalink
♻️ Refactor transactions context and storage to use localStorage ♻️
Browse files Browse the repository at this point in the history
  • Loading branch information
Aszurar committed Jan 17, 2024
1 parent 6f41fe2 commit 16908f3
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 55 deletions.
113 changes: 68 additions & 45 deletions src/context/transactions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,51 @@ import React, {
useEffect,
useMemo,
useReducer,
useState,
// useState,
} from 'react'
// import { api } from '../../server/api'
import {
ITransactions,
PeriodBalanceProps,
TRANSACTIONS_REDUCER_INITIAL_STATE,
} from '../../dto/transactions'
import { transactionsReducer } from '../../reducers/transactions/reducer'
import { api } from '../../server/api'
import {
addTransaction,
calculateBalance,
calculateIncomeTotal,
calculateOutcomeTotal,
getLastIncomeTransaction,
getLastOutcomeTransaction,
getPeriodBalance,
loadTransactions,
// loadTransactions,
removeTransactionById,
} from '../../reducers/transactions/actions'
import { dateFormatterMedium } from '../../utils/formatter'
import {
differenceInDays,
differenceInMonths,
differenceInYears,
} from 'date-fns'
import { getAllTransactions } from '../../storage/transactions/getAllTransactions'
import { registerAllTransactions } from '../../storage/transactions/registerAllTransactions'

type PeriodBalanceFormattedProps = {
period: string
dates: PeriodBalanceProps
}

type IsDeleteTransactionLoadingProps = {
id: string
value: boolean
}
// type IsDeleteTransactionLoadingProps = {
// id: string
// value: boolean
// }
interface TransactionsContextProps {
transactions: ITransactions[]
incomeTotal: number
outcomeTotal: number
balance: number
isAddTransactionLoading: boolean
isDeleteTransactionLoading: IsDeleteTransactionLoadingProps
// isAddTransactionLoading: boolean
// isDeleteTransactionLoading: IsDeleteTransactionLoadingProps
periodBalanceFormatted?: PeriodBalanceFormattedProps
lastIncomeTransactionDateFormatted: string
lastOutcomeTransactionDateFormatted: string
Expand All @@ -56,25 +60,33 @@ interface TransactionsProviderProps {
children: React.ReactNode
}

const INITIAL_IS_DELETE_TRANSACTION_LOADING_VALUE = {
id: '',
value: false,
}
// const INITIAL_IS_DELETE_TRANSACTION_LOADING_VALUE = {
// id: '',
// value: false,
// }

const TransactionsContext = createContext({} as TransactionsContextProps)

function TransactionsProvider({
children,
}: Readonly<TransactionsProviderProps>) {
const [isDeleteTransactionLoading, setIsDeleteTransactionLoading] =
useState<IsDeleteTransactionLoadingProps>(
INITIAL_IS_DELETE_TRANSACTION_LOADING_VALUE,
)
const [isAddTransactionLoading, setIsAddTransactionLoading] = useState(false)
// This branch will not use json-server, but localStorage
// const [isDeleteTransactionLoading, setIsDeleteTransactionLoading] =
// useState<IsDeleteTransactionLoadingProps>(
// INITIAL_IS_DELETE_TRANSACTION_LOADING_VALUE,
// )
// const [isAddTransactionLoading, setIsAddTransactionLoading] = useState(false)

const [transactionsState, dispatch] = useReducer(
transactionsReducer,
TRANSACTIONS_REDUCER_INITIAL_STATE,
() => {
const transactions = getAllTransactions()
return {
...TRANSACTIONS_REDUCER_INITIAL_STATE,
transactions,
}
},
)
const {
balance,
Expand Down Expand Up @@ -143,29 +155,38 @@ function TransactionsProvider({
return undefined
}, [periodBalance])

async function loadTransactionsData() {
const response = await api.get('/transactions')
const data: ITransactions[] = response.data ? response.data : []
dispatch(loadTransactions(data))
}

const addNewTransaction = useCallback(async (transaction: ITransactions) => {
setIsAddTransactionLoading(true)
await api.post('/transactions', transaction)
loadTransactionsData()
setIsAddTransactionLoading(false)
const handleAddNewTransaction = useCallback((transaction: ITransactions) => {
dispatch(addTransaction(transaction))
}, [])

const removeTransactionById = useCallback(async (id: string) => {
setIsDeleteTransactionLoading({ id, value: true })
await api.delete(`/transactions/${id}`)
loadTransactionsData()
setIsDeleteTransactionLoading({ id, value: false })
const handleRemoveTransactionById = useCallback((id: string) => {
dispatch(removeTransactionById(id))
}, [])

useEffect(() => {
loadTransactionsData()
}, [])
// This branch will not use json-server, but localStorage
// async function loadTransactionsData() {
// const response = await api.get('/transactions')
// const data: ITransactions[] = response.data ? response.data : []
// dispatch(loadTransactions(data))
// }

// const addNewTransaction = useCallback(async (transaction: ITransactions) => {
// setIsAddTransactionLoading(true)
// await api.post('/transactions', transaction)
// loadTransactionsData()
// setIsAddTransactionLoading(false)
// }, [])

// const removeTransactionById = useCallback(async (id: string) => {
// setIsDeleteTransactionLoading({ id, value: true })
// await api.delete(`/transactions/${id}`)
// loadTransactionsData()
// setIsDeleteTransactionLoading({ id, value: false })
// }, [])

// useEffect(() => {
// loadTransactionsData()
// }, [])

useEffect(() => {
dispatch(calculateIncomeTotal())
Expand All @@ -174,6 +195,8 @@ function TransactionsProvider({
dispatch(getLastIncomeTransaction())
dispatch(getLastOutcomeTransaction())
dispatch(getPeriodBalance())

registerAllTransactions(transactions)
}, [transactions])

const contextValue = useMemo(
Expand All @@ -183,23 +206,23 @@ function TransactionsProvider({
transactions,
outcomeTotal,
periodBalanceFormatted,
isAddTransactionLoading,
isDeleteTransactionLoading,
// isAddTransactionLoading,
// isDeleteTransactionLoading,
lastIncomeTransactionDateFormatted,
lastOutcomeTransactionDateFormatted,
handleAddNewTransaction: addNewTransaction,
handleRemoveTransactionById: removeTransactionById,
handleAddNewTransaction,
handleRemoveTransactionById,
}),
[
balance,
incomeTotal,
transactions,
outcomeTotal,
addNewTransaction,
removeTransactionById,
handleAddNewTransaction,
handleRemoveTransactionById,
periodBalanceFormatted,
isAddTransactionLoading,
isDeleteTransactionLoading,
// isAddTransactionLoading,
// isDeleteTransactionLoading,
lastIncomeTransactionDateFormatted,
lastOutcomeTransactionDateFormatted,
],
Expand Down
8 changes: 4 additions & 4 deletions src/reducers/transactions/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function loadTransactions(transactions: ITransactions[]) {
} satisfies IActions
}

function addNewTransaction(transaction: ITransactions) {
function addTransaction(transaction: ITransactions) {
return {
type: ActionTypes.ADD_TRANSACTION,
payload: {
Expand All @@ -59,7 +59,7 @@ function addNewTransaction(transaction: ITransactions) {
} satisfies IActions
}

function removeTransaction(id: string) {
function removeTransactionById(id: string) {
return {
type: ActionTypes.REMOVE_TRANSACTION,
payload: {
Expand Down Expand Up @@ -108,8 +108,8 @@ export {
ActionTypes,
calculateBalance,
loadTransactions,
addNewTransaction,
removeTransaction,
addTransaction,
removeTransactionById,
calculateIncomeTotal,
calculateOutcomeTotal,
getLastIncomeTransaction,
Expand Down
5 changes: 3 additions & 2 deletions src/storage/storageConfig.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const DT_MONEY_THEME = '@dt-money:theme-1.0.0'
const TRANSACTIONS_COLLECTION = '@dtmoney:transactions-1.0.0'
const APP_THEME = '@dtmoney:theme-1.0.0'

export { DT_MONEY_THEME }
export { TRANSACTIONS_COLLECTION, APP_THEME }
4 changes: 2 additions & 2 deletions src/storage/theme/getTheme.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ITheme, THEME } from '../../dto/theme'
import { DT_MONEY_THEME } from '../storageConfig'
import { APP_THEME } from '../storageConfig'

export function getTheme() {
const response = localStorage.getItem(DT_MONEY_THEME)
const response = localStorage.getItem(APP_THEME)

const theme = response ? JSON.parse(response) : THEME.light

Expand Down
4 changes: 2 additions & 2 deletions src/storage/theme/updateTheme.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ITheme } from '../../dto/theme'
import { DT_MONEY_THEME } from '../storageConfig'
import { APP_THEME } from '../storageConfig'

export function updateTheme(theme: ITheme) {
localStorage.setItem(DT_MONEY_THEME, JSON.stringify(theme))
localStorage.setItem(APP_THEME, JSON.stringify(theme))
}
8 changes: 8 additions & 0 deletions src/storage/transactions/getAllTransactions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { ITransactions } from '../../dto/transactions'
import { TRANSACTIONS_COLLECTION } from '../storageConfig'

export function getAllTransactions(): ITransactions[] {
const storage = localStorage.getItem(TRANSACTIONS_COLLECTION)

return storage ? JSON.parse(storage) : ([] as ITransactions[])
}
6 changes: 6 additions & 0 deletions src/storage/transactions/registerAllTransactions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ITransactions } from '../../dto/transactions'
import { TRANSACTIONS_COLLECTION } from '../storageConfig'

export function registerAllTransactions(transactions: ITransactions[]) {
localStorage.setItem(TRANSACTIONS_COLLECTION, JSON.stringify(transactions))
}

0 comments on commit 16908f3

Please sign in to comment.