afraid-scarlet
afraid-scarlet6mo 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.ai6mo 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.ai6mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
afraid-scarlet
afraid-scarlet6mo 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.ai6mo 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.ai6mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
afraid-scarlet
afraid-scarlet6mo ago
@kapa.ai Can I learn to SWR?
kapa.ai
kapa.ai6mo 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.ai6mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
afraid-scarlet
afraid-scarlet6mo 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.ai6mo 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.ai6mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
afraid-scarlet
afraid-scarlet6mo 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.ai6mo 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.ai6mo ago
<@1184365192482652173> kapa.ai is still learning and improving, please let us know how it did by reacting below
afraid-scarlet
afraid-scarlet6mo 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."