How to refresh page after deleting an item using REDUX/RTK Query?
Asked Answered
A

3

6

I am fetching data from my api using RTK Query like this

    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));

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.

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

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? 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));

    }
  };
Amaro answered 15/10, 2021 at 22:56 Comment(0)
I
8

Normally, you can use providesTags and invalidatedTags withing RTK-Query to make related queries automatically refetch after a mutation is run. In your case, your delete is not a mutation, but you can still use that mechanism.

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.

  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) {
Initial answered 16/10, 2021 at 7:7 Comment(3)
Without refetching, how to modify the existing state. Sometimes we might have 100 data, after adding one data, refetching whole data might be inefficient. How to handle this?Suborder
@JeevanandanJ check this redux-toolkit.js.org/rtk-query/usage/manual-cache-updatesIsoline
Really, Thank you so much @Irfanwani. I found the same too, but didn't forget to update the comment.Suborder
P
1

A general way to refetch:

const MyComponent = () =>{


  const { refetch, data, error, isFetching} = useGetGithubByNameQuery();


  const toRender = error ? (
    <p>Oh no, there was an error</p>
  ) : isFetching ? (
    <p>"Loading..."</p>
  ) : data ? (
    data.map((item)=>{return <p>item.toString()</p>})
  ) : null;


  return(
    <>
      {toRender}
      <button onClick={refetch}>Refresh</button>
    </>
  )
}
Paleolith answered 22/10, 2022 at 13:34 Comment(0)
S
0

You should read this example https://redux-toolkit.js.org/rtk-query/usage/examples. Notice that provideTags and invalidatesTags.

Strategy answered 11/10, 2022 at 9:23 Comment(1)
Found no mention on provideTags, invalidatesTags.Edile

© 2022 - 2024 — McMap. All rights reserved.