rrubiorr81
rrubiorr81

Reputation: 305

how to specify when to re-trigger hook

I'm trying to update my react tool knowledge, adding RTK

Was going over the overview for RTK Query https://redux-toolkit.js.org/rtk-query/overview

and ended up with somwthing like this:

export const todoApi = createApi({
  reducerPath: 'todoApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com/' }),
  endpoints: (builder) => ({
    getAllTodos: builder.query<Task[], string>({
      query: () => `todos`,
    }),
  }),
})

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetAllTodosQuery } = todoApi

in the slice:

export const todoSlice = createSlice({
  name: "todo",
  initialState,
  reducers: {
    addTask: //[...],
    toggleTask: // [...],
    fillTodos: (state, action: PayloadAction<Task[]>) => {
      // debugger;
      state.todos = action.payload
    }
  }
});

so, finally in the component, I'm trying to pull from the API:

export function Todo() {

  const todos = useSelector((state: RootState) => state.todo.todos);
  const dispatch = useDispatch();

  
    const { data, error, isLoading } = useGetAllTodosQuery("")
    if (data) {
      dispatch(fillTodos(data));
    }

This would roughly work, updating the store with the pulled todos, but it would trigger the useGetAllTodosQuery every time the component re-renders (even several times while mounting or when updating the store with an unrelated action -like to complete a task-). Kinda was looking for a similar to useEffect param to specify when to trigger the effect again. I guess I'm missing some basics.

Ideas? Thanks!

Upvotes: 0

Views: 772

Answers (1)

phry
phry

Reputation: 44196

It actually does not refetch multiple times. It fetches once.

And then data is in the cache and it does not make a request until you manually call .refetch on the result, or use the automatic refetching feature with providesTags/invalidatesTags.

If you want to get deeper into RTK Query, follow chapter 7 and 8 of the official Redux tutorial

PS: you should not really copy that data out of RTK Query into your own slices if you can avoid it. Just call the use...Query hook with the same argument everywhere you need that data.

Upvotes: 1

Related Questions