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!