Home > Enterprise >  React | How to use hook functions in callback functions
React | How to use hook functions in callback functions

Time:01-10

I am implementing the paging function, click the next page to get the data again, but the function to get the data is a hook function, what should I do?

import React, { useRef, useEffect, useState, useCallback } from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
import { useGetArticlesQuery } from '../../store/api/articleApi'

const App = () => {
  const onChange: PaginationProps['onChange'] = (page) => {
    setCurrent(page);
    // I want to get articles data through hook useGetArticlesQuery but fail
    // const { data, isSuccess } = useGetArticlesQuery()
  };
  <Pagination current={current} onChange={onChange} total={total} defaultPageSize={amount} />
}

CodePudding user response:

maybe you should rethink the architecture of your app.

try to use the base of the code below and adjust according to your needs


import React, { useEffect, useState } from 'react';

const App = () => {

useEffect(() => {
const options = //...

fetch('https://xxxxxxxx/api/getAllArticles/page=${page}', options)
      .then((response) => response.json())
      .then((data) => {
        console.log('Success:', data);
        setData(data)
      })
      .catch((error) => {
        console.error(error);
      });

}, [page, data])
  
const [page, setPage] = useState(0);
const [data, setData] = useState(null);

//..... other logic

return (
// .. all articles
// .. pagination onClick = setPage(// next page)
)
}

good luck!

CodePudding user response:

Hook Can only be used in top level of one component.

So you can't use hook in components callback function.

You can do like below:

import React, { useRef, useEffect, useState, useCallback } from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
import { useGetArticlesQuery } from '../../store/api/articleApi'

const App = () => {
  const { fetchData } = useGetArticlesQuery()
  const onChange: PaginationProps['onChange'] = (page) => {
    setCurrent(page);
    fetchData(page)
  };
  <Pagination
    current={current}
    onChange={onChange}
    total={total}
    defaultPageSize={amount}
  />
}

  • Related