<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Himanshu Gupta</title>
    <description>The latest articles on DEV Community by Himanshu Gupta (@himanshu_gupta_50a71f4bac).</description>
    <link>https://dev.to/himanshu_gupta_50a71f4bac</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1504616%2F36b707be-83da-4a70-bc7a-2e01e199655c.png</url>
      <title>DEV Community: Himanshu Gupta</title>
      <link>https://dev.to/himanshu_gupta_50a71f4bac</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/himanshu_gupta_50a71f4bac"/>
    <language>en</language>
    <item>
      <title>Building a To-Do App with RTK Query</title>
      <dc:creator>Himanshu Gupta</dc:creator>
      <pubDate>Sun, 19 May 2024 10:08:07 +0000</pubDate>
      <link>https://dev.to/himanshu_gupta_50a71f4bac/building-a-to-do-app-with-rtk-query-2p4a</link>
      <guid>https://dev.to/himanshu_gupta_50a71f4bac/building-a-to-do-app-with-rtk-query-2p4a</guid>
      <description>&lt;p&gt;In this guide, we'll walk you through creating a simple To-Do application using RTK Query, a powerful data fetching and caching tool from Redux Toolkit. We'll use an open-source API to manage our to-dos. By the end of this guide, you'll have a fully functional To-Do app and a solid understanding of how to integrate RTK Query in your projects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before we start, make sure you have the following installed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node.js&lt;/li&gt;
&lt;li&gt;npm or yarn&lt;/li&gt;
&lt;li&gt;A code editor (e.g., VSCode)&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Step 1: Setting Up the Project&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;1. Initialize a new React project:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app rtk-query-todo
cd rtk-query-todo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Install necessary dependencies:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @reduxjs/toolkit react-redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Step 2: Setting Up RTK Query&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;1. Create an API slice:&lt;/strong&gt;&lt;br&gt;
     First, let's create an API slice to manage our To-Do operations. We'll use the &lt;a href="https://jsonplaceholder.typicode.com/"&gt;JSONPlaceholder API&lt;/a&gt; for demonstration purposes.&lt;/p&gt;

&lt;p&gt;Create a file named &lt;strong&gt;apiSlice.js&lt;/strong&gt; in the &lt;strong&gt;&lt;u&gt;src&lt;/u&gt;&lt;/strong&gt; directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/apiSlice.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const apiSlice = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com/' }),
  endpoints: (builder) =&amp;gt; ({
    getTodos: builder.query({
      query: () =&amp;gt; 'todos',
    }),
    addTodo: builder.mutation({
      query: (newTodo) =&amp;gt; ({
        url: 'todos',
        method: 'POST',
        body: newTodo,
      }),
    }),
    deleteTodo: builder.mutation({
      query: (id) =&amp;gt; ({
        url: `todos/${id}`,
        method: 'DELETE',
      }),
    }),
  }),
});

export const { useGetTodosQuery, useAddTodoMutation, useDeleteTodoMutation } = apiSlice;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Configure the store:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, let's configure our Redux store to include the API slice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/app/store.js
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from '../apiSlice';

export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
  },
  middleware: (getDefaultMiddleware) =&amp;gt;
    getDefaultMiddleware().concat(apiSlice.middleware),
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Provide the store to your app:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Wrap your application with the Redux provider in &lt;strong&gt;index.js&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';
import './index.css';

ReactDOM.render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;Provider store={store}&amp;gt;
      &amp;lt;App /&amp;gt;
    &amp;lt;/Provider&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;,
  document.getElementById('root')
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Step 3: Creating the To-Do Components&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;1. Create a To-Do List component:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/components/TodoList.js
import React from 'react';
import { useGetTodosQuery, useDeleteTodoMutation } from '../apiSlice';

const TodoList = () =&amp;gt; {
  const { data: todos, error, isLoading } = useGetTodosQuery();
  const [deleteTodo] = useDeleteTodoMutation();

  if (isLoading) return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;
  if (error) return &amp;lt;p&amp;gt;Error loading todos&amp;lt;/p&amp;gt;;

  return (
    &amp;lt;ul&amp;gt;
      {todos.map((todo) =&amp;gt; (
        &amp;lt;li key={todo.id}&amp;gt;
          {todo.title}
          &amp;lt;button onClick={() =&amp;gt; deleteTodo(todo.id)}&amp;gt;Delete&amp;lt;/button&amp;gt;
        &amp;lt;/li&amp;gt;
      ))}
    &amp;lt;/ul&amp;gt;
  );
};

export default TodoList;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Create an Add To-Do component:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/components/AddTodo.js
import React, { useState } from 'react';
import { useAddTodoMutation } from '../apiSlice';

const AddTodo = () =&amp;gt; {
  const [title, setTitle] = useState('');
  const [addTodo] = useAddTodoMutation();

  const handleSubmit = async (e) =&amp;gt; {
    e.preventDefault();
    if (title) {
      await addTodo({
        title,
        completed: false,
      });
      setTitle('');
    }
  };

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;input
        type="text"
        value={title}
        onChange={(e) =&amp;gt; setTitle(e.target.value)}
        placeholder="Add a new todo"
      /&amp;gt;
      &amp;lt;button type="submit"&amp;gt;Add Todo&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
};

export default AddTodo;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Combine components in the main App:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/App.js
import React from 'react';
import TodoList from './components/TodoList';
import AddTodo from './components/AddTodo';

function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;h1&amp;gt;RTK Query To-Do App&amp;lt;/h1&amp;gt;
      &amp;lt;AddTodo /&amp;gt;
      &amp;lt;TodoList /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Step 4: Running the Application&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, you can run your application using the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your application should be up and running at &lt;a href="http://localhost:3000"&gt;http://localhost:3000&lt;/a&gt;. You can add new to-dos and delete existing ones using the JSONPlaceholder API.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Conclusion&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this guide, we covered how to create a simple To-Do application using RTK Query with an open-source API. We set up our Redux store, created API slices, and built components for listing and adding to-dos. RTK Query simplifies data fetching and caching, making it easier to manage server-side data in your applications.&lt;/p&gt;

&lt;p&gt;Feel free to expand on this project by adding more features such as editing to-dos, marking them as completed, or integrating user authentication. Happy coding!&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
