【问题标题】:useSWR to get get data of specific ID使用SWR获取特定ID的数据
【发布时间】:2022-02-23 17:36:42
【问题描述】:

我正在使用带有 SWR 的 NextJS,并且我想使用 SWR 获取一个特定 ID 的数据。 当用户点击表格行时,它将从服务器中提取具有该 ID 的数据。

下面是 SWR 代码

export const apiExpenses = () => {

    const { data: showExpense, error, mutate } = useSWR('/api/expenses/show', () =>
    axios
        .get('/api/expenses/show/' + expenseId)
        .then(res => res.data)
  )

  return {
    showExpense,
  }
};

下面的代码是另一个调用showExpense的组件,

const { showExpense } = apiExpenses();

const clickTo = async (expenseId) => {

    //How can i fetch data with specific ID in SWR?
    const expenseData = //Code?
  };

  //In JSX

  <IconButton onClick={() => clickTo(params.id)} color="primary">

我不确定如何将expenseId 传递给 SWR API。

谢谢,

【问题讨论】:

    标签: reactjs next.js swr


    【解决方案1】:

    首先你需要将expenseId 传递给钩子:

    export const apiExpenses = (expenseId) => {
    
        // You need to pass id to the swr hook, not to axios, otherwise it wont refetch data for another id
        const { data: showExpense, error, mutate } = useSWR(
          // Pass null when there is no id
          expenseId ? ('/api/expenses/show/' + expenseId) : null,
          (key) => axios.get(key).then(res => res.data)
      )
    
      return {
        showExpense,
      }
    };
    

    另一方面,您可以将当前 id 存储在状态中:

    const [currentId, setCurrentId] = useState()
    const { showExpense } = apiExpenses(currentId);
    
    const clickTo = async (expenseId) => {
        setCurrentId(expenseId)
      };
    
      //In JSX
    
      <IconButton onClick={() => clickTo(params.id)} color="primary">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 2019-10-26
      • 1970-01-01
      相关资源
      最近更新 更多