Last active
May 31, 2022 05:35
-
-
Save sourabhbagrecha/ee6c69fec1d43e045f2f9d125d4e21f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useContext } from 'react'; | |
import request, { gql } from 'graphql-request'; | |
import PageContainer from "../components/PageContainer.component"; | |
import { UserContext } from '../contexts/user.context'; | |
import { GRAPHQL_ENDPOINT } from '../realm/constants'; | |
import ExpenseCard from '../components/ExpenseCard.component'; | |
import useAuthedQuery from '../hooks/useAuthedQuery'; | |
const Home = () => { | |
const { user } = useContext(UserContext); | |
const getAllExpensesQuery = gql` | |
query getAllExpenses { | |
expenses(sortBy: CREATEDAT_DESC) { | |
_id | |
title | |
amount | |
mode | |
category | |
createdAt | |
} | |
} | |
`; | |
const queryVariables = {}; | |
const headers = { Authorization: `Bearer ${user._accessToken}` } | |
const loadExpenses = () => request(GRAPHQL_ENDPOINT, | |
getAllExpensesQuery, | |
queryVariables, | |
headers | |
); | |
// Now, instead of using useQuery as we were doing before. | |
// We will now be using the useAuthedQuery with the same options | |
// and same return object as before but with improved error handling. | |
const { isLoading, error, data, refetch } = useAuthedQuery("allExpenses", loadExpenses); | |
const afterDelete = () => { | |
refetch(); | |
}; | |
if (isLoading) return "Loading"; | |
if (error) return error.message; | |
return <PageContainer> | |
<h1>All Expenses</h1> | |
{ | |
data.expenses | |
.map(expense => ({ ...expense, key: expense._id, afterDelete })) | |
.map(expense => <ExpenseCard {...expense} />) | |
} | |
</PageContainer> | |
} | |
export default Home; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment