4๐
โ
As requested please find below a basic common approach with a React / Django setup:
- Make an (async) API request in React to your Django endpoint/view (in this case Iโm using standard fetch API)
- Map the returned JSON to create DOM elements for rendering
import PayrollRuns from "./PayrollRuns";
import PayrollDetails from "./PayrollDetails";
import {useEffect, useState} from "react";
import moment from "moment";
const PayrollWrapper = () => {
// Set State for Payroll data
const [payrollRuns, setPayrollRuns] = useState([])
// Fetch data --> 1.)
useEffect(() => {
// Fetch the Payroll Data related to the logged in User
fetch(`http://127.0.0.1:8000/api/lastpayrollruns/`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${localStorage.getItem('token')}`
},
})
.then(res => res.json())
.then(data => {
setPayrollRuns(data)
});
}, []);
// --> 2.)
const runItems = props.payrollRuns.map((run) =>
<div key={run.id} className="flex justify-between p-2 text-lg text-base">
<div>
{moment(run.month.period).format('YYYY MMMM')}:
Paid {run.payroll_run_items.length} talents
</div>
<div>
{run.payroll_run_items.reduce((acc, value) => {
return parseFloat(value.amount.toFixed(2)) + acc; // Add 'value.amount' to 'acc'
}, 0)}
</div>
</div>
);
return (
<div className="runs-wrapper bg-white rounded-xl h-full w-48 shadow-sx-shadow p-4 flex flex-col">
<h1 className="border-b-2 pb-4">Payroll Runs</h1>
<div className="grow overflow-auto p-4">{runItems}</div>
</div>
)
}
export default PayrollWrapper
Django API endpoint/view for the given example:
class PayrollRun(APIView):
"""
Retrieve payroll runs including line items for a company
"""
def get(self, request):
company = Company.objects.get(userprofile__user=request.user)
payroll_runs = Payroll.objects.filter(company=company).order_by('-month')
serializer = PayrollSerializer(payroll_runs, many=True)
return Response(serializer.data)
Note:
One key concept of this setup is to provide the authentication header (token) for the API request as you will want to access the Django authenticated user (request.user)
object in your views to make the database queries according to the user on client side.
๐คJSRB
Source:stackexchange.com