> For the complete documentation index, see [llms.txt](https://adam-37.gitbook.io/joomadeung/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adam-37.gitbook.io/joomadeung/react-2/rtk-rtk-query/rtk-rtk-query-basic.md).

# RTK / RTK Query Basic

`createAction`두 가지 인수를 취합니다. 첫 번째는 작업 유형이며 필수입니다. 두 번째 인수는 소위 `prepare`로, 결과 작업 생성자로부터 인수를 수락하고 이러한 인수를 추가 데이터로 작업 개체에 첨부하는 데 사용할 수 있습니다. *준비* 기능은 선택 사항입니다 .

`createAction` takes two arguments. The first one is the action type and it's required. The second argument is a so-called *prepare* function which wecan use to accept arguments from the resulting action creator and attach these arguments as additional data to the action object. The *prepare* function is optional.

[Redux Toolkit - A Simple Example Workflow](https://levelup.gitconnected.com/redux-toolkit-a-simple-example-workflow-20efcee54635)

***

`extraReducers` allows `createSlice` to respond to other action types besides the types it has generated.

`extraReducers`를 사용하면 `createSlice`가 생성한 작업 유형 이외의 다른 작업 유형에 응답할 수 있습니다.

As case reducers specified with `extraReducers`  are meant to reference "external" actions, they will not have actions generated in `slice.actions`.

As with `reducers` , these case reducers will also be passed to `createReducer`  and may "mutate" their state safely.

The recommended way of using `extraReducers`  is to use a callback that receives a `ActionReducerMapBuilder`  instance.

***

`unwrap()`

we can `await addNewPost().unwrap()` to handle any potential errors with a standard `try/catch`  block.

***

RTK Query

```tsx
export const postsApi = createApi({
  reducerPath: "posts",
  baseQuery: fetchBaseQuery({
    baseUrl: '/api',
    prepareHeaders: (headers) => { // 비동기 로직도 작성할 수 있습니다.
      ...
      return headers;
    },
  })
  tagTypes: ["Post List"],  // 캐싱에 사용될 태그의 타입
  endpoints: (build) => ({
    getPosts: build.query({  // HTTP GET의 경우
      query: () => ({ url: "posts" }),
      provideTags: [{ type: "Post List" }],  // 받아온 데이터에 태그 부여
    }),
    postPost: build.mutation({  // POST, PATCH, DELETE 등의 경우
      query: (body) => {
        return {
          url: "/posts",
          method: "POST",
          body,
        };
      },
      invalidateTags: [{ type: "Post List" }],  // 해당 태그를 가진 캐시 데이터 제거(타입 체크도 자동으로 됨)
    }),
  }),
});
```

***

`invalidatesTags`를 추가해 데이터가 삭제가 되면 자동으로 패치되도록 합니다.

```tsx
deleteTodo: builder.mutation({
      query: (id: number) => ({
        url: `/todo/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: ['Todos'],
    }),
```

Get all todos

query: () => endpoint

providesTags는 invalidatesTags가 실행될 때 자동으로 패치될 쿼리

```tsx
getAllTodos: builder.query<TodoModel[], String>({
      query: () => '/allTodos',
      providesTags: ['Todos'],
    }),
```
