https://github.com/masum184e/redux_rtk_query_basic_template
This repository provides a foundational structure for implementing CRUD (Create, Read, Update, Delete) operations using Redux Toolkit Query. Whether you're building a new application or seeking to enhance an existing one, this template offers a streamlined approach to managing data fetching.
https://github.com/masum184e/redux_rtk_query_basic_template
data-fetching react-redux redux redux-data-fetching redux-rtk-query redux-toolkit rtk-query
Last synced: about 1 month ago
JSON representation
This repository provides a foundational structure for implementing CRUD (Create, Read, Update, Delete) operations using Redux Toolkit Query. Whether you're building a new application or seeking to enhance an existing one, this template offers a streamlined approach to managing data fetching.
- Host: GitHub
- URL: https://github.com/masum184e/redux_rtk_query_basic_template
- Owner: masum184e
- Created: 2024-04-02T12:55:12.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-04-19T06:07:56.000Z (about 1 year ago)
- Last Synced: 2025-02-06T07:11:17.275Z (3 months ago)
- Topics: data-fetching, react-redux, redux, redux-data-fetching, redux-rtk-query, redux-toolkit, rtk-query
- Language: JavaScript
- Homepage: https://redux-rtk-query-basic-template.vercel.app
- Size: 85 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Redux RTK Query Basic Template
RTK Query is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
## Preview
![]()
Live View## Requirements
[Install Node On Your Device](https://nodejs.org/)
## Installation
```
npm install @reduxjs/toolkit react-redux
```## How to Run
```
git clone https://github.com/masum184e/redux_rtk_query_basic_template.git
cd redux_rtk_query_basic_template
npm install
npm run dev
```## Explaination
We bassically need 4 different component:
1. **provider:**
The Provider component is provided by the react-redux library, which is the official React bindings for Redux. It is used at the top level of your React component tree to wrap your entire application. By doing so, it makes the Redux store available to all components in the application without needing to pass it explicitly through props at each level.
```jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import { Provider } from 'react-redux'
import { store } from '../redux/store.js'
import "./index.css"ReactDOM.createRoot(document.getElementById('root')).render(
,
)2. **store:**
In Redux, the store is a central piece of the architecture that holds the state of your entire application. It serves as a single source of truth for your data.
```jsx
import { configureStore } from '@reduxjs/toolkit';
import { setupListeners } from '@reduxjs/toolkit/query';
import { postApiSlice } from './slice/post';export const store = configureStore({
reducer: {
[postApiSlice.reducerPath]: postApiSlice.reducer
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(postApiSlice.middleware)
});setupListeners(store.dispatch);
3. **slice:**
Slices play a crucial role in managing the cache and fetching data from APIs. RTK Query simplifies data fetching and caching by automatically generating slices for you based on the endpoints you define.
```jsx
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';export const postApiSlice = createApi({
reducerPath: 'postApi',
baseQuery: fetchBaseQuery({
baseUrl: import.meta.env.VITE_API_URL
}),endpoints: (builder) => ({
getAllPost: builder.query({
query: () => ({
url: "posts",
method: "GET"
})
}),
deletePost: builder.mutation({
query: (postId) => ({
url: `posts/${postId}`,
method: 'DELETe'
})
}),
addPost: builder.mutation({
query: (newPost) => ({
url: "posts",
method: 'POST',
body: newPost
})
})
})
})export const { useGetAllPostQuery, useDeletePostMutation, useAddPostMutation } = postApiSlice;
4. **consumer:**
RTK Query automatically generates hooks for each endpoint you define using the `createApi` function. These hooks are named according to the convention `use{EndpointName}Query`, `use{EndpointName}Mutation` etc. Once you have fetched data using a query hook, you can consume it directly in your React components. The hook returns an object containing properties such as `data`, `isLoading`, `isFetching`, `error`, etc., which represent the current state of the data fetching process.
```jsx
import { useState } from 'react';
import { useAddPostMutation, useGetAllPostQuery } from './../../redux/slice/post';const Form = () => {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');const [addPost] = useAddPostMutation();
const { refetch } = useGetAllPostQuery();const handleSubmit = async (e) => {
e.preventDefault();
try {
await addPost({ title, description });
setTitle('');
setDescription('');
await refetch();
} catch (error) {
console.error('Error adding post:', error);
}
};return (
<>
Title
setTitle(e.target.value)} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required/>
Description
setDescription(e.target.value)} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline resize-none h-32" required>
Submit
>
);
};export default Form;
## Structure
```
├─ redux
│ ├─ store.js
│ ├─ slice
│ └─ post.js
│
├─ src
│ ├─components
│ │ ├─ Form.jsx
│ │ └─ List.jsx
│ │
│ ├─ App.jsx
│ ├─ index.css
│ └─ main.jsx
│
├─ .env
├─ .eslintrc.cjs
├─ .gitignore
├─ index.html
├─ package-lock.json
├─ postcss.config.js
├─ preview.png
├─ README.md
├─ tailwind.config.js
├─ vercel.json
└─ vite.config.js
```