sunny-green
sunny-green3mo ago

How can I refresh data periodically?

<Grid item xs={24} lg={12}>
<List
headerButtons={<ExportButton onClick={triggerExport} loading={exportLoading} />}
title={'적립금 지급 내역'}
wrapperProps={{ sx: { paddingX: { xs: 2, md: 0 } } }}
>
<Typography variant="body1" align="right">
* 주문건에 대한 상세 내용이나, 클레임 처리, 구독신청 내역 확인 등은 기존 카페24 관리자 페이지에서 진행해
주세요.
</Typography>
{open && <PointsDetail open={open} onClose={handleClose} pointDetail={pointDetail} />}
<DataGrid
{...dataGridProps}
columns={columns}
filterModel={undefined}
autoHeight
pageSizeOptions={[10, 20, 50, 100]}
rowHeight={80}
sx={{
...dataGridProps.sx,
'& .MuiDataGrid-row': {
cursor: 'pointer',
},
}}
/>
</List>
</Grid>
</Grid>
)
}

export const getServerSideProps: GetServerSideProps<{}> = async (context) => {
const { authenticated, redirectTo } = await authProvider.check(context)
const translateProps = await serverSideTranslations(context.locale ?? 'ko', ['common'])

const pointResponse = await fetch(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, {
headers: {
'Content-Type': 'application/json',
},
})

const points = await pointResponse.json()

if (!authenticated) {
return {
props: {},
redirect: {
destination: redirectTo,
permanent: false,
},
}
}
console.log(points)
return {
props: {
points,
...translateProps,
},
}
}
<Grid item xs={24} lg={12}>
<List
headerButtons={<ExportButton onClick={triggerExport} loading={exportLoading} />}
title={'적립금 지급 내역'}
wrapperProps={{ sx: { paddingX: { xs: 2, md: 0 } } }}
>
<Typography variant="body1" align="right">
* 주문건에 대한 상세 내용이나, 클레임 처리, 구독신청 내역 확인 등은 기존 카페24 관리자 페이지에서 진행해
주세요.
</Typography>
{open && <PointsDetail open={open} onClose={handleClose} pointDetail={pointDetail} />}
<DataGrid
{...dataGridProps}
columns={columns}
filterModel={undefined}
autoHeight
pageSizeOptions={[10, 20, 50, 100]}
rowHeight={80}
sx={{
...dataGridProps.sx,
'& .MuiDataGrid-row': {
cursor: 'pointer',
},
}}
/>
</List>
</Grid>
</Grid>
)
}

export const getServerSideProps: GetServerSideProps<{}> = async (context) => {
const { authenticated, redirectTo } = await authProvider.check(context)
const translateProps = await serverSideTranslations(context.locale ?? 'ko', ['common'])

const pointResponse = await fetch(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, {
headers: {
'Content-Type': 'application/json',
},
})

const points = await pointResponse.json()

if (!authenticated) {
return {
props: {},
redirect: {
destination: redirectTo,
permanent: false,
},
}
}
console.log(points)
return {
props: {
points,
...translateProps,
},
}
}
29 Replies
kapa.ai
kapa.ai3mo ago
Hi @florent. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- I'm sorry, but the provided knowledge sources do not contain information on how to refresh data periodically in Refine. However, you can consider using a state management library or React's built-in hooks to manage state and trigger re-renders when your data changes. For more detailed information, you can refer to the official Refine documentation (https://refine.dev/docs/getting-started/introduction). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai
export const getServerSideProps: GetServerSideProps<{}> = async (context) => {
const { authenticated, redirectTo } = await authProvider.check(context)
const translateProps = await serverSideTranslations(context.locale ?? 'ko', ['common'])

const pointResponse = await fetch(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, {
headers: {
'Content-Type': 'application/json',
},
})

const points = await pointResponse.json()

const interval = setInterval(fetchData, 10000)
if (!authenticated) {
return {
props: {},
redirect: {
destination: redirectTo,
permanent: false,
},
}
}
console.log(points)
return {
props: {
points,
...translateProps,
},
}
}
export const getServerSideProps: GetServerSideProps<{}> = async (context) => {
const { authenticated, redirectTo } = await authProvider.check(context)
const translateProps = await serverSideTranslations(context.locale ?? 'ko', ['common'])

const pointResponse = await fetch(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, {
headers: {
'Content-Type': 'application/json',
},
})

const points = await pointResponse.json()

const interval = setInterval(fetchData, 10000)
if (!authenticated) {
return {
props: {},
redirect: {
destination: redirectTo,
permanent: false,
},
}
}
console.log(points)
return {
props: {
points,
...translateProps,
},
}
}
Can I query the data again using interval here?
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The getServerSideProps function in Next.js is a server-side rendering function that runs at build time in production. It won't be able to set an interval to fetch data periodically because it's not running in the browser. If you want to fetch data periodically, you should do it on the client-side, in a React component, using hooks like useEffect. However, please note that this is not a recommended practice as it can lead to unnecessary requests and load on your server. Instead, consider using a real-time data fetching library or use a state management library like React Query or SWR that supports background updates and caching. For more information, you can refer to the Refine documentation (https://refine.dev/docs/getting-started/introduction) and the React Query guide (https://refine.dev/blog/react-query-guide). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai Can I learn to SWR?
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, you can definitely learn to use SWR. It's a powerful client-side data fetching library used in modern web applications. It's particularly useful in React-based applications and comes with features like automatic revalidation, focus tracking, and error retries. Here are some steps to get started with SWR: 1. Understand the basics of JavaScript and React, as SWR is a library for use with React and its frameworks. Make sure you have Node (https://nodejs.org/) installed on your computer. 2. Create a new React project with create-react-app:
npx create-react-app my-swr

npx create-react-app my-swr

or with Yarn:
yarn create react-app my-swr

yarn create react-app my-swr

3. Install the necessary packages for your application. In this case, you would need styled-components and swr:
npm install styled-components swr

npm install styled-components swr

or with Yarn:
yarn add styled-components swr

yarn add styled-components swr

4. Start learning how to fetch data with SWR and compare it with other data fetching methods like the native 'Fetch() API' or Axios. 5. Explore additional features of SWR like TypeScript support and developer tools for debugging and writing your code more efficiently. You can find more detailed information and a step-by-step guide in this blog post (https://refine.dev/blog/data-fetching-next-js-useswr). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
export default function PointList() {
type PointDetail = IPointDetailItem[] | ''
const [pointDetail, setPointDetail] = useState<PointDetail>('')
const [open, setOpen] = React.useState(false)
const [startValue, setStartValue] = React.useState<Dayjs | null>(null)
const [endValue, setEndValue] = React.useState<Dayjs | null>(null)
const handleClose = () => setOpen(false)



const handleOpen = (pointDetail: PointDetail) => {
setPointDetail(pointDetail)
setOpen(true)

}

const { dataGridProps, search, filters } = useDataGrid<BaseRecord, HttpError, IPointsFilterVariables>({
pagination: {
mode: 'server',
},
initialPageSize: 10,
onSearch: (params) => {
const filters: CrudFilters = []
const { q, points } = params

filters.push({
field: 'q',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push({
field: 'points',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push(
{
field: 'order_date',
operator: 'gte',
value: startValue ? dayjs(startValue).format('YYYY-MM-DD 00:00:00') : undefined,
},
{
field: 'order_date',
operator: 'lte',
value: endValue ? dayjs(endValue).format('YYYY-MM-DD 23:59:59') : undefined,
},
)

return filters
},
})
export default function PointList() {
type PointDetail = IPointDetailItem[] | ''
const [pointDetail, setPointDetail] = useState<PointDetail>('')
const [open, setOpen] = React.useState(false)
const [startValue, setStartValue] = React.useState<Dayjs | null>(null)
const [endValue, setEndValue] = React.useState<Dayjs | null>(null)
const handleClose = () => setOpen(false)



const handleOpen = (pointDetail: PointDetail) => {
setPointDetail(pointDetail)
setOpen(true)

}

const { dataGridProps, search, filters } = useDataGrid<BaseRecord, HttpError, IPointsFilterVariables>({
pagination: {
mode: 'server',
},
initialPageSize: 10,
onSearch: (params) => {
const filters: CrudFilters = []
const { q, points } = params

filters.push({
field: 'q',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push({
field: 'points',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push(
{
field: 'order_date',
operator: 'gte',
value: startValue ? dayjs(startValue).format('YYYY-MM-DD 00:00:00') : undefined,
},
{
field: 'order_date',
operator: 'lte',
value: endValue ? dayjs(endValue).format('YYYY-MM-DD 23:59:59') : undefined,
},
)

return filters
},
})
How to apply useSWR in this code? @kapa.ai export default function PointList() { type PointDetail = IPointDetailItem[] | '' const [pointDetail, setPointDetail] = useState<PointDetail>('') const [open, setOpen] = React.useState(false) const [startValue, setStartValue] = React.useState<Dayjs | null>(null) const [endValue, setEndValue] = React.useState<Dayjs | null>(null) const handleClose = () => setOpen(false) const handleOpen = (pointDetail: PointDetail) => { setPointDetail(pointDetail) setOpen(true) } const { dataGridProps, search, filters } = useDataGrid<BaseRecord, HttpError, IPointsFilterVariables>({ pagination: { mode: 'server', }, initialPageSize: 10, onSearch: (params) => { const filters: CrudFilters = [] const { q, points } = params filters.push({ field: 'q', operator: 'eq', value: q !== '' ? q : undefined, }) filters.push({ field: 'points', operator: 'eq', value: q !== '' ? q : undefined, }) filters.push( { field: 'order_date', operator: 'gte', value: startValue ? dayjs(startValue).format('YYYY-MM-DD 00:00:00') : undefined, }, { field: 'order_date', operator: 'lte', value: endValue ? dayjs(endValue).format('YYYY-MM-DD 23:59:59') : undefined, }, ) return filters }, }) How to apply useSWR in this code?
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To apply useSWR in your code, you would need to replace the data fetching logic with a useSWR hook. However, the provided code and knowledge sources do not contain enough information to provide a specific example of how to replace your existing data fetching logic with useSWR. In general, you would use useSWR like this:
import useSWR from 'swr'

function YourComponent() {
const { data, error } = useSWR('/api/data', fetcher)

if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>

// render your data
}
import useSWR from 'swr'

function YourComponent() {
const { data, error } = useSWR('/api/data', fetcher)

if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>

// render your data
}
In this example, '/api/data' is the key for your data (usually the API endpoint), and fetcher is a function that returns a Promise with your data. useSWR will ensure that your component re-renders when the data changes. For more detailed information on how to use useSWR, you can refer to the SWR documentation (https://swr.vercel.app/docs/getting-started). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai how to writing a fetcher?
export default function PointList() {
const fetcher = (url) => fetch(url).then((res) => res.json())

const { data, error } = useSWR('/api/data', { initialData: props.data });




export const getServerSideProps: GetServerSideProps<{}> = async (context) => {
const { authenticated, redirectTo } = await authProvider.check(context)
const translateProps = await serverSideTranslations(context.locale ?? 'ko', ['common'])

const pointResponse = await fetch(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, {
headers: {
'Content-Type': 'application/json',
},
})

const points = await pointResponse.json()

if (!authenticated) {
return {
props: {},
redirect: {
destination: redirectTo,
permanent: false,
},
}
}

return {
props: {
points,
...translateProps,
},
}
}
export default function PointList() {
const fetcher = (url) => fetch(url).then((res) => res.json())

const { data, error } = useSWR('/api/data', { initialData: props.data });




export const getServerSideProps: GetServerSideProps<{}> = async (context) => {
const { authenticated, redirectTo } = await authProvider.check(context)
const translateProps = await serverSideTranslations(context.locale ?? 'ko', ['common'])

const pointResponse = await fetch(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, {
headers: {
'Content-Type': 'application/json',
},
})

const points = await pointResponse.json()

if (!authenticated) {
return {
props: {},
redirect: {
destination: redirectTo,
permanent: false,
},
}
}

return {
props: {
points,
...translateProps,
},
}
}
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- In your code, you've already written a fetcher function. The fetcher function is a function that fetches data from a given URL and returns a Promise that resolves with the data. Here's how you've defined it:
const fetcher = (url) => fetch(url).then((res) => res.json())
const fetcher = (url) => fetch(url).then((res) => res.json())
This fetcher uses the Fetch API to get data from the provided URL, and then it converts the response to JSON. You're using this fetcher with useSWR like this:
const { data, error } = useSWR('/api/data', fetcher);
const { data, error } = useSWR('/api/data', fetcher);
In this line, useSWR is called with two arguments: the key ('/api/data') and the fetcher function. The key is a unique identifier for the data (usually the API endpoint), and the fetcher function is responsible for getting the data. If you want to use the data fetched in getServerSideProps as the initial data for your SWR hook, you can pass it as initialData in the options object:
const { data, error } = useSWR('/api/data', fetcher, { initialData: props.points });
const { data, error } = useSWR('/api/data', fetcher, { initialData: props.points });
In this case, props.points should be the data fetched in getServerSideProps. For more detailed information on how to use useSWR, you can refer to the SWR documentation (https://swr.vercel.app/docs/getting-started). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai I fix this code
export default function PointList() {
const { data, error } = useSWR(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, { initialData: props.data });

export default function PointList() {
const { data, error } = useSWR(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, { initialData: props.data });

but return error this. "No overload matches this call. The last overload gave the following error. Object literal may only specify known properties, and 'initialData' does not exist in type 'SWRConfiguration<any, any, BareFetcher<any>>'.ts(2769) index.d.ts(200, 5): The last overload is declared here."
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message is indicating that initialData is not a recognized property in the configuration object for useSWR. This is because the initialData option is not directly supported by useSWR. Instead, useSWR provides a fallbackData option that you can use to specify initial data. Here's how you can modify your code:
export default function PointList() {
const { data, error } = useSWR(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, fetcher, { fallbackData: props.data });
}
export default function PointList() {
const { data, error } = useSWR(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, fetcher, { fallbackData: props.data });
}
In this case, props.data should be the data you want to use as the initial data. For more detailed information on how to use useSWR, you can refer to the SWR documentation (https://swr.vercel.app/docs/options). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai When the value is added, swr operates normally. However, it does not change when the value is modified.
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- SWR automatically revalidates data when you navigate back to a page or when you focus on a page. However, it doesn't automatically revalidate data when the data changes on the server. If you want to revalidate data when a certain event happens (like when data is modified), you can use the mutate function from SWR. The mutate function allows you to trigger a revalidation manually. Here's a basic example:
import useSWR, { mutate } from 'swr'

function YourComponent() {
const { data, error } = useSWR('/api/data', fetcher)

const updateData = async () => {
// mutate current data to optimistically update the UI instantly
mutate('/api/data', newData, false)
// send a request to the API to update the source
await requestUpdateToAPI(newData)
// trigger a revalidation to ensure the local data is correct
mutate('/api/data')
}

// ...
}
import useSWR, { mutate } from 'swr'

function YourComponent() {
const { data, error } = useSWR('/api/data', fetcher)

const updateData = async () => {
// mutate current data to optimistically update the UI instantly
mutate('/api/data', newData, false)
// send a request to the API to update the source
await requestUpdateToAPI(newData)
// trigger a revalidation to ensure the local data is correct
mutate('/api/data')
}

// ...
}
In this example, mutate is used to update the local data instantly and then revalidate it with the server data. For more detailed information on how to use mutate with useSWR, you can refer to the SWR documentation (https://swr.vercel.app/docs/mutation). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai Can the data be refreshed every 3 seconds?
return (
<SWRConfig
value={{
refreshInterval: 3000,
fetcher: (resource, init) => fetch(resource, init).then(res => res.json())
}}
>
<RefineKbarProvider>
<ColorModeContextProvider>
<CssBaseline />
<GlobalStyles styles={{ html: { WebkitFontSmoothing: 'auto' } }} />
<RefineSnackbarProvider>
<DevtoolsProvider>
<Refine
i18nProvider={i18nProvider}
authProvider={authProvider}
routerProvider={routerProvider}
dataProvider={{ default: dataProvider(API_URL!) }}
accessControlProvider={accessControlProvider}
notificationProvider={notificationProvider}
resources={[
{
name: 'customergroups',
list: '/customergroups',
meta: {
label: '혜택 관리',
canDelete: true,
},
},
{
name: 'points',
list: '/points',
meta: {
label: '적립금 관리',
canDelete: false,
},
},
]}
options={{
syncWithLocation: true,
warnWhenUnsavedChanges: true,
useNewQueryKeys: true,
projectId: 'WGjJEg-44uEu3-5kTmc4',
}}
>
{renderComponent()}
<RefineKbar />
<UnsavedChangesNotifier />
<DocumentTitleHandler />
</Refine>
<DevtoolsPanel />
</DevtoolsProvider>
</RefineSnackbarProvider>
</ColorModeContextProvider>
</RefineKbarProvider>
</SWRConfig>
)
}
return (
<SWRConfig
value={{
refreshInterval: 3000,
fetcher: (resource, init) => fetch(resource, init).then(res => res.json())
}}
>
<RefineKbarProvider>
<ColorModeContextProvider>
<CssBaseline />
<GlobalStyles styles={{ html: { WebkitFontSmoothing: 'auto' } }} />
<RefineSnackbarProvider>
<DevtoolsProvider>
<Refine
i18nProvider={i18nProvider}
authProvider={authProvider}
routerProvider={routerProvider}
dataProvider={{ default: dataProvider(API_URL!) }}
accessControlProvider={accessControlProvider}
notificationProvider={notificationProvider}
resources={[
{
name: 'customergroups',
list: '/customergroups',
meta: {
label: '혜택 관리',
canDelete: true,
},
},
{
name: 'points',
list: '/points',
meta: {
label: '적립금 관리',
canDelete: false,
},
},
]}
options={{
syncWithLocation: true,
warnWhenUnsavedChanges: true,
useNewQueryKeys: true,
projectId: 'WGjJEg-44uEu3-5kTmc4',
}}
>
{renderComponent()}
<RefineKbar />
<UnsavedChangesNotifier />
<DocumentTitleHandler />
</Refine>
<DevtoolsPanel />
</DevtoolsProvider>
</RefineSnackbarProvider>
</ColorModeContextProvider>
</RefineKbarProvider>
</SWRConfig>
)
}
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, you can set the refreshInterval option in the SWRConfig to refresh the data every 3 seconds. This option sets the interval (in milliseconds) at which SWR should re-fetch data. In your code, you've set refreshInterval to 3000, which means SWR will re-fetch the data every 3 seconds:
<SWRConfig
value={{
refreshInterval: 3000,
fetcher: (resource, init) => fetch(resource, init).then(res => res.json())
}}
>
{/* ... */}
</SWRConfig>
<SWRConfig
value={{
refreshInterval: 3000,
fetcher: (resource, init) => fetch(resource, init).then(res => res.json())
}}
>
{/* ... */}
</SWRConfig>
This setting will apply to all useSWR hooks in your application. If you want to set a different refresh interval for a specific useSWR hook, you can do so by passing an options object to the hook:
const { data, error } = useSWR('/api/data', fetcher, { refreshInterval: 5000 });
const { data, error } = useSWR('/api/data', fetcher, { refreshInterval: 5000 });
In this example, the data will be refreshed every 5 seconds, regardless of the refreshInterval set in SWRConfig. For more detailed information on how to use refreshInterval with useSWR, you can refer to the SWR documentation (https://swr.vercel.app/docs/options#refreshinterval). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai
export default function PointList() {
const fetcher = (url:any) => fetch(url).then((res) => res.json())
const { data, error } = useSWR(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, fetcher, { refreshInterval: 5000 });

type PointDetail = IPointDetailItem[] | ''
const [pointDetail, setPointDetail] = useState<PointDetail>('')
const [open, setOpen] = React.useState(false)
const [startValue, setStartValue] = React.useState<Dayjs | null>(null)
const [endValue, setEndValue] = React.useState<Dayjs | null>(null)
const handleClose = () => setOpen(false)

const handleOpen = (pointDetail: PointDetail) => {
setPointDetail(pointDetail)
setOpen(true)

}

const { dataGridProps, search, filters } = useDataGrid<BaseRecord, HttpError, IPointsFilterVariables>({
pagination: {
mode: 'server',
},
initialPageSize: 10,
onSearch: (params) => {
const filters: CrudFilters = []
const { q, points } = params

filters.push({
field: 'q',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push({
field: 'points',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push(
{
field: 'order_date',
operator: 'gte',
value: startValue ? dayjs(startValue).format('YYYY-MM-DD 00:00:00') : undefined,
},
{
field: 'order_date',
operator: 'lte',
value: endValue ? dayjs(endValue).format('YYYY-MM-DD 23:59:59') : undefined,
},
)

return filters
},
})
export default function PointList() {
const fetcher = (url:any) => fetch(url).then((res) => res.json())
const { data, error } = useSWR(`${process.env.NEXT_PUBLIC_PUBLIC_IP}/points`, fetcher, { refreshInterval: 5000 });

type PointDetail = IPointDetailItem[] | ''
const [pointDetail, setPointDetail] = useState<PointDetail>('')
const [open, setOpen] = React.useState(false)
const [startValue, setStartValue] = React.useState<Dayjs | null>(null)
const [endValue, setEndValue] = React.useState<Dayjs | null>(null)
const handleClose = () => setOpen(false)

const handleOpen = (pointDetail: PointDetail) => {
setPointDetail(pointDetail)
setOpen(true)

}

const { dataGridProps, search, filters } = useDataGrid<BaseRecord, HttpError, IPointsFilterVariables>({
pagination: {
mode: 'server',
},
initialPageSize: 10,
onSearch: (params) => {
const filters: CrudFilters = []
const { q, points } = params

filters.push({
field: 'q',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push({
field: 'points',
operator: 'eq',
value: q !== '' ? q : undefined,
})

filters.push(
{
field: 'order_date',
operator: 'gte',
value: startValue ? dayjs(startValue).format('YYYY-MM-DD 00:00:00') : undefined,
},
{
field: 'order_date',
operator: 'lte',
value: endValue ? dayjs(endValue).format('YYYY-MM-DD 23:59:59') : undefined,
},
)

return filters
},
})
I am receiving data through datagrid. How do I change this to data received from swr?
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To use the data received from SWR in your useDataGrid hook, you can pass the data from SWR as the initialData option in useDataGrid. However, please note that the useDataGrid hook from Refine does not directly support an initialData option. Refine's useDataGrid hook is designed to work with Refine's data provider system, which abstracts the data fetching process and provides a unified interface for different backends. It's not directly compatible with SWR's data fetching model. If you want to use SWR for data fetching in a Refine application, you would need to create a custom data provider that uses SWR under the hood. This would involve implementing the various methods (like getList, getOne, create, update, etc.) using SWR's useSWR or mutate functions. Here's a very basic example of what a custom data provider using SWR might look like:
import { fetcher } from './fetcher'; // Your SWR fetcher
import useSWR from 'swr';

const swrDataProvider = {
getList: (resource, params) => {
const { data, error } = useSWR(`/api/${resource}`, fetcher);
return { data, error };
},
// Implement other methods...
};

export default swrDataProvider;
import { fetcher } from './fetcher'; // Your SWR fetcher
import useSWR from 'swr';

const swrDataProvider = {
getList: (resource, params) => {
const { data, error } = useSWR(`/api/${resource}`, fetcher);
return { data, error };
},
// Implement other methods...
};

export default swrDataProvider;
Then, you can use this data provider in your Refine application:
<Refine dataProvider={swrDataProvider}>
{/* Your app */}
</Refine>
<Refine dataProvider={swrDataProvider}>
{/* Your app */}
</Refine>
Please note that this is a simplified example and a real implementation would need to handle parameters, errors, and other aspects properly. For more information on how to create a custom data provider in Refine, you can refer to the Refine documentation (https://refine.dev/docs/data/data-provider#how-can-i-customize-existing-data-providers). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
sunny-green
sunny-green3mo ago
@kapa.ai dataProvider this. How to fix?
export const dataProvider = (apiUrl: string, httpClient: AxiosInstance = axiosInstance): DataProvider => ({
getList: async ({ resource, pagination, filters, sorters, meta }) => {
const url = `${apiUrl}/${resource}`
const fetcher = (url:any) => fetch(url).then((res) => res.json())
const { data, error } = useSWR(`/api/${resource}`, fetcher);

const { current = 1, pageSize = 10, mode = 'server' } = pagination ?? {}

const { headers: headersFromMeta, method } = meta ?? {}
const requestMethod = (method as MethodTypes) ?? 'get'

const queryFilters = generateFilter(filters)

const query: {
_start?: number
_end?: number
_sort?: string
_order?: string
} = {}

if (mode === 'server') {
query._start = (current - 1) * pageSize
query._end = current * pageSize
}

const generatedSort = generateSort(sorters)
if (generatedSort) {
const { _sort, _order } = generatedSort
query._sort = _sort.join(',')
query._order = _order.join(',')
}

const { data, headers } = await httpClient[requestMethod](`${url}?${stringify(query)}&${stringify(queryFilters)}`, {
headers: headersFromMeta,
})

const total = data.total

return {
data: data.data,
total: total || data.data.length,
}
},
export const dataProvider = (apiUrl: string, httpClient: AxiosInstance = axiosInstance): DataProvider => ({
getList: async ({ resource, pagination, filters, sorters, meta }) => {
const url = `${apiUrl}/${resource}`
const fetcher = (url:any) => fetch(url).then((res) => res.json())
const { data, error } = useSWR(`/api/${resource}`, fetcher);

const { current = 1, pageSize = 10, mode = 'server' } = pagination ?? {}

const { headers: headersFromMeta, method } = meta ?? {}
const requestMethod = (method as MethodTypes) ?? 'get'

const queryFilters = generateFilter(filters)

const query: {
_start?: number
_end?: number
_sort?: string
_order?: string
} = {}

if (mode === 'server') {
query._start = (current - 1) * pageSize
query._end = current * pageSize
}

const generatedSort = generateSort(sorters)
if (generatedSort) {
const { _sort, _order } = generatedSort
query._sort = _sort.join(',')
query._order = _order.join(',')
}

const { data, headers } = await httpClient[requestMethod](`${url}?${stringify(query)}&${stringify(queryFilters)}`, {
headers: headersFromMeta,
})

const total = data.total

return {
data: data.data,
total: total || data.data.length,
}
},
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The useSWR hook cannot be used inside a data provider function because useSWR is a React hook and must follow the Rules of Hooks (https://reactjs.org/docs/hooks-rules.html). Hooks can only be called inside the body of a function component or a custom hook. In your case, you're trying to use useSWR inside the getList method of your data provider, which is not a component or a custom hook. This is why you're getting an error. Instead of using useSWR inside your data provider, you should continue using the httpClient (axios instance) to make HTTP requests as you're currently doing. The useSWR hook is meant to be used inside your components to fetch data and automatically update your UI when the data changes. Here's how you can modify your getList method to use axios:
getList: async ({ resource, pagination, filters, sorters, meta }) => {
const url = `${apiUrl}/${resource}`

const { current = 1, pageSize = 10, mode = 'server' } = pagination ?? {}

const { headers: headersFromMeta, method } = meta ?? {}
const requestMethod = (method as MethodTypes) ?? 'get'

const queryFilters = generateFilter(filters)

const query: {
_start?: number
_end?: number
_sort?: string
_order?: string
} = {}

if (mode === 'server') {
query._start = (current - 1) * pageSize
query._end = current * pageSize
}

const generatedSort = generateSort(sorters)
if (generatedSort) {
const { _sort, _order } = generatedSort
query._sort = _sort.join(',')
query._order = _order.join(',')
}

const { data, headers } = await httpClient**requestMethod** (`${url}?${stringify(query)}&${stringify(queryFilters)}`, {
headers: headersFromMeta,
})

const total = data.total

return {
data: data.data,
total: total || data.data.length,
}
},
getList: async ({ resource, pagination, filters, sorters, meta }) => {
const url = `${apiUrl}/${resource}`

const { current = 1, pageSize = 10, mode = 'server' } = pagination ?? {}

const { headers: headersFromMeta, method } = meta ?? {}
const requestMethod = (method as MethodTypes) ?? 'get'

const queryFilters = generateFilter(filters)

const query: {
_start?: number
_end?: number
_sort?: string
_order?: string
} = {}

if (mode === 'server') {
query._start = (current - 1) * pageSize
query._end = current * pageSize
}

const generatedSort = generateSort(sorters)
if (generatedSort) {
const { _sort, _order } = generatedSort
query._sort = _sort.join(',')
query._order = _order.join(',')
}

const { data, headers } = await httpClient**requestMethod** (`${url}?${stringify(query)}&${stringify(queryFilters)}`, {
headers: headersFromMeta,
})

const total = data.total

return {
data: data.data,
total: total || data.data.length,
}
},
In this code, httpClient[requestMethod] is used to make the HTTP request, and the response is returned as the result of the getList method. This is the correct way to implement a data provider in Refine. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below