简体   繁体   English

使用 REDUX/RTK 查询删除项目后如何刷新页面?

[英]How to refresh page after deleting an item using REDUX/RTK Query?

I am fetching data from my api using RTK Query like this我正在使用这样的 RTK 查询从我的 api 中获取数据

    export const coinApi = createApi({
  reducerPath: 'coinApi',
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCoins: builder.query({
      query: () => createRequest(`/watchlist`),
    })

  }),
});

and im deleting a coin from my table like this我像这样从我的桌子上删除一枚硬币

export const deleteCoin = (id) => async (dispatch, getState) => {


try {
    dispatch({
      type: COIN_DELETE_REQUEST,
    });

    await axios.delete(`/api/coins/watchlist/${id}`);

    dispatch({
      type: COIN_DELETE_SUCCESS,
    });
  } catch (error) {
    const message =
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message;
    dispatch({
      type: COIN_DELETE_FAIL,
      payload: message,
    });
  }
};

and in my frontEnd component: I am calling dispatch(deleteCoin(id));在我的前端组件中:我正在调用 dispatch(deleteCoin(id));

the delete functionality is working, since in my database it is removed however the component does not refresh so the coin still exists on the UI unless I refresh the page myself manually.删除功能正在运行,因为在我的数据库中它已被删除,但是组件不会刷新,因此除非我自己手动刷新页面,否则该硬币仍然存在于 UI 上。

I've tried accessing the global data from the RTK query, but cannot do it successfully I was trying to use useEffect and pass in the dependency data from我已经尝试从 RTK 查询访问全局数据,但无法成功我试图使用 useEffect 并从

const { data, isFetching } = useGetCoinsQuery(); const { data, isFetching } = useGetCoinsQuery();

However its still not reloading my component?但是它仍然没有重新加载我的组件? How else can i reload my component?我还能如何重新加载我的组件? This is my first time using RTK Query so I'm not sure how to really access that data and how can it listen to data changes in teh API server?这是我第一次使用 RTK 查询,所以我不确定如何真正访问该数据以及它如何侦听 API 服务器中的数据更改? Thanks谢谢

 const coins = useSelector((state) => state.coinApi.queries)
  const {
    loading: loadingDelete,
    error: errorDelete,
    success: successDelete,
  } = coinDelete;

  useEffect(() => {}, [dispatch, successDelete, data]);

  if (isFetching) return <Loader></Loader>;

  const deleteHandler = (id) => {
    if (window.confirm('Are you sure?')) {
      dispatch(deleteCoin(id));

    }
  };

Normally, you can use providesTags and invalidatedTags withing RTK-Query to make related queries automatically refetch after a mutation is run.通常情况下, 你可以使用providesTagsinvalidatedTags withing RTK-查询,使运行的突变后,相关查询自动重新提取。 In your case, your delete is not a mutation, but you can still use that mechanism.在您的情况下,您的delete不是突变,但您仍然可以使用该机制。

In the long run I would encourage you to make a mutation out of your delete action here though, since RTK-Query will work a lot better the more you do in there - and you won't have to have all that code written by hand.从长远来看,我会鼓励您在此处对delete操作进行更改,因为 RTK-Query 的工作效果会更好,您在其中执行的操作越多 - 而且您不必手动编写所有代码.

  baseQuery: fetchBaseQuery({ baseUrl }),
  tagTypes: ['Coins'],
  endpoints: (builder) => ({
    getCoins: builder.query({
      query: () => createRequest(`/watchlist`),
      providesTags: [ 'Coins' ]
    })
   await axios.delete(`/api/coins/watchlist/${id}`);

    dispatch({
      type: COIN_DELETE_SUCCESS,
    });
    dispatch(api.util.invalidateTags(['Coins'])) // this will refetch all queries that "provide" the tag `"Coins"`
  } catch (error) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM