The Expenses component

The list of expenses retrieved from the database will be rendered using a React component called Expenses. This component, on the initial load, will render the expenses incurred by the signed-in user in the current month. In this view, the user will also have the option to pick a date range to retrieve expenses incurred within specific dates, as shown in the following screenshot:

While defining the Expenses component, we first use a useEffect hook to make a fetch call to the list expenses API in order to retrieve the initial list of expenses. We also initialize the values that are necessary for making this request and for rendering the response to be received from the server, as shown in the following code.

mern-expense-tracker/client/expense/Expenses.js:

export default function Expenses() {
const date = new Date(), y = date.getFullYear(), m = date.getMonth()
const [firstDay, setFirstDay] = useState(new Date(y, m, 1))
const [lastDay, setLastDay] = useState(new Date(y, m + 1, 0))

const jwt = auth.isAuthenticated()
const [redirectToSignin, setRedirectToSignin] = useState(false)
const [expenses, setExpenses] = useState([])

useEffect(() = {
const abortController = new AbortController()
const signal = abortController.signal
listByUser({firstDay: firstDay, lastDay: lastDay},
{t: jwt.token}, signal)
.then((data) = {
if (data.error) {
setRedirectToSignin(true)
} else {
setExpenses(data)
}
})
return function cleanup(){
abortController.abort()
}
}, [])
...
}

We first determine the dates of the first day and the last day of the current month. These dates are set in the state to be rendered in the search form fields and provided as the date range query parameters in the request to the server. Because we will only fetch the expenses associated with the current user, we retrieve the signed-in user's auth credentials to be sent with the request. If the request to the server results in an error, we will redirect the user to the login page. Otherwise, we will set the received expenses in the state to be rendered in the view.

In the view part of the Expenses component, we will add a form to search by date range, before iterating through the resulting expenses array to render individual expense details. In the following sections, we will look at the implementation of the search form and expenses list in the component view.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset