What is It?
TANStack Query হল একটা technology যা data fetching and caching process গুলোতে আরও সহজ এবং effective করে তুলে। It is actually a library for managing data fetching and mutation operations with ease. The main purpose of TANStack Query is to simplify data fetching processes. It provides a convenient and advanced feature set that helps you manage data fetching and mutation operations effortlessly.
The key components of TANStack Query are the “useQuery” and “useMutation” hooks. The “useQuery” hook is used to define queries, which simplifies data fetching processes and allows you to control the expected data reactivity. The “useMutation” hook is used to define mutation operations, making it easier to update the main data and control the expected data reactivity.
Are Tanstack query, axios, fetch same?
না , TANStack Query, Axios এবং Fetch এগুলো same না, although they serve similar purposes of making HTTP requests and retrieving data from APIs. Here are the differences between them:
- TANStack Query: TANStack Query is a specific library that provides a set of hooks and utilities for data fetching and caching in React applications. It is built on top of Axios and Fetch but offers additional features such as automatic caching, data refetching, pagination support, and optimistic updates. TANStack Query simplifies data fetching and state management by providing a higher-level abstraction and integration with React components.
- Axios: Axios is a popular JavaScript library used for making HTTP requests from the browser or Node.js. It provides a simple and elegant API for sending and receiving data from APIs. Axios supports various features like interceptors, request/response transformations, and error handling. It does not include built-in caching or data management capabilities like TANStack Query.
- Fetch: Fetch is a built-in browser API for making HTTP requests. It provides a simpler and more modern alternative to XMLHttpRequest (XHR). Fetch allows you to make requests and receive responses from APIs, but it is lower-level compared to Axios and TANStack Query. Fetch provides basic functionality for sending and receiving data but lacks some of the advanced features and convenience provided by Axios and TANStack Query.
In summary, TANStack Query is a library that builds upon Axios and Fetch to provide enhanced data fetching and caching capabilities specifically for React applications. Axios is a standalone library for making HTTP requests with additional features, while Fetch is a browser API for basic HTTP requests.
CRUD operations
উপরের github লিঙ্ক এ গিয়ে create, read, delete, update operation গুলো code দেখে নিতে পারেন। Component wise আলাদা করে দেওয়া আছে। এখানে সেগুলোর explanation দেওয়া হল।
Read Operation (Posts.jsx):
const { data: posts, isLoading, isError } = useQuery({
queryKey: ['posts'],
queryFn: async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
const data = await response.data;
return data;
},
retry: 3,
})
if (isLoading) return (<h1>Loading….</h1>)
if (isError) return (<h1>Error loading data!!!</h1>)
- Parameters of
useQuery
hook :useQuery
hook টি data fetching process সম্পন্ন করার জন্য ব্যবহার করা হয়। এটা একটা object কে initial value হিসেবে accept করবে। Object এর কিছু specific property থাকবে।
queryKey
: query করার পর data কোন key তে store হবে সেটা এখানে বলে দেওয়া হয়, আপনি আলাদা আলাদা api থেকে data load করার জন্য যদি একই queryKey সব জায়গায় use করেন, তাহলে error দিবে। queryKey আলাদা আলাদা হতে হবে। In this case, the key is['posts']
, indicating that the query is fetching data related to posts. React Query তে মূলত key ব্যবহার করা হয় আইডেন্টিফাই করার জন্য আর রেজাল্ট কে ক্যাশ করে রাখার জন্য। মানে হল React Query দিয়ে চিনতে পারবো যে আমাদের ডাটা টা কোথা আসতেছে পাশাপাশি আমাদের পরবর্তী ব্যবহারের React Query ডাটাকে cache বা সংরক্ষণ করে রাখেই। এই key যেকোন কিছু হতে পারে। আমরা মূলত similar নাম ব্যবহার করি সহজে বুঝতে পারার জন্য। রিয়াক্ট কুয়েরি দিয়ে আমাদের ক্লাইন্ট সাইটে ডাটাকে cache করে রাখা যায়। যার কারণে আমাদেরকে বারবার refetchকরার প্রয়োজন হয় না। যখন আমাদের কোন কোম্পনেন্ট ওই ডাটা ব্যবহার করে তখন React Query ওই unique key এর মাধ্যমে চেক করে যে ওই ডাটা অলরেডি আছে কিনা যদি থাকে তাহলে সে ডাটাকে রিটার্ন করে দেয় যার ফলে unnecessary network requests হয়না। যদি কখনো এই key পরিবর্তন হয় তাহলে রিয়েক্ট কুয়েরি বুঝতে পারে যে তাকে refetchকরতে হবে।queryFn
: এটা একটা asynchronous function যার মাধ্যমে actual API request করা হয়। এই example এ, Axios ব্যবহার করা হয়েছে GET request করে data fetch করার জন্য এই 'https://jsonplaceholder.typicode.com/posts' থেওে। একই কাজ আপনি axios এর বদলে fetch use করেও করতে পারবেন। তার মানে একটা জিনিস খেয়াল করেছেন? আপনিuseEffect
hook এর মধ্যে axios/ fetch use করে data load করতে পারতেন, এখনuseEffect
না করেuseQuery
এর মধ্যে করছেন।retry
: আপনার data fetch করার সময় network issue / server error / অন্য কোন কারণে দুই তিনবার data load ঠিকমত নাও হতে পারে। অনেক সময় দেখা যায় কিছুক্ষন wait করলে / website এ একটা refresh করলে data load হচ্ছে। এই কিছুক্ষন wait করে refresh করার কাজটি আপনার আর manually করতে হচ্ছে না। retry এর value যত দিবেন, automatically ততবার সেটি server থেকে data load করার try করবে। In this case, the value is set to 3, meaning that the query will retry up to 3 times before considering it as a failure.
2. Response from the useQuery
hook:
data
: এটা server থেকে fetch করা data একটা array এর মধ্যে store করে।data:posts
এভাবে না লিখে আপনি এটা চাইলে এভাবেও লিখতে পারেনdata:posts[]
isLoading
: Data server থেকে আসতে কিছুটা সময় লাগে, এটাকে বলা হয় loading state. Loading state (isLoading
) true মানে data এখনও fetch হয় নি। In that case, the code returns a<h1>Loading....</h1>
element to indicate that the data is being loaded and the user should wait.isError
: Server থেকে data fetching এর সময় কোনও ধরনের error হল কিনা সেটাisError
এর সাহায্যে track রাখা হয়। If it's true, it means an error occurred. In that case, the code returns a<h1>Error loading data!!!</h1>
element to inform the user about the error.
By using the isLoading
and isError
variables, the code can handle the different states of the data fetching process and provide appropriate feedback to the user, whether it's displaying a loading message or an error message. ভেবে দেখুন, এই useQuery
ব্যবহার না করলে কিন্তু এই state সবগুলো ( isLoading
, isError
etc.) আপনাকে useState
দিয়ে manually handle করতে হত।
Create, delete, update Operations (AddPost.jsx / UpdatePost.jsx/ DeletePst.jsx):
আপনি data post, put, patch, delete related যেই কাজ ই করতে চাইবেন, সব গুলতেই আপনাকে দুইটা hook use করে করতে হবে। useQueryClient
and useMutation।
তার ভেতর আপনি axios/ fetch etc. use করে data post, put, patch, delete related tasks করবেন। তো এখানে simple রাখার জন্য আমি post operation টা explain করে দিচ্ছি।
const addPost = async (data) => {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', data);
return response.data;
};
const queryClient = useQueryClient();
const mutation = useMutation(addPost, {
onSuccess: () => {
console.log("added")
queryClient.invalidateQueries('posts');
},
});
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
mutation.mutate(Object.fromEntries(formData));
};
addPost
function হল একটা asynchronous function parameter হিসেবে নিবেdata
ডাটা র মধ্যে সেই information থাকবে যা আপনি database এ post করতে চাচ্ছেন। তারপর server এ data post করতে আপনি axios/ fetch etc. যা ইচ্ছে use করতে পারেন। 'https://jsonplaceholder.typicode.com/posts' এবংdata
টা request body তে দিয়ে দিতে হবে। The response is then accessed usingresponse.data
and returned from the function.- The
useQueryClient
hook এটা খুব গুরুত্বপূর্ণ যা query client instance ( In TANStack query, the query client instance is an object that acts as a central hub for managing the cache, handling data fetching operations, and providing various functions and utilities related to querying data ) কে access করতে সাহায্য করবে। - The
useMutation
hook is used to define a mutation operation. এর সাহায্যে আপনি server এ ডাটা modify (create, delete, post, patch, put) করতে পারবেন। - Within the
useMutation
hook, an object is provided as the second argument, which includes a property calledonSuccess
. TheonSuccess
property specifies a function that will be executed when the mutation is successful. - In this case, the
onSuccess
function logs a message to the console indicating that the post has been successfully added. Additionally, it uses thequeryClient.invalidateQueries()
method to invalidate the cache for the 'posts' query. এটা ensure করবে যেন একটা new post add হবার পর 'posts' query এর জন্য যেই cache আছে সেটা updat হয়। আর এটা internally refetch function কে trigger করার মাধ্যমে হয়ে থাকে। - The
handleSubmit
function is a callback function that is executed when a form is submitted. It prevents the default form submission behavior, extracts the form data usingFormData
, and then calls themutation.mutate()
function to initiate the mutation operation. TheObject.fromEntries(formData)
converts the FormData object into a plain JavaScript object before passing it to the mutation function.
By using the useMutation
hook, the code enables the submission of a form to add a new post. The mutation function (addPost
) is called when the form is submitted, and the onSuccess
function is triggered upon successful mutation. যদি mutation successfully হয়, তাহলে এই hook বিভিন্ন side effects handling এর মত কাজগুল করে, যেমন updating the cache and performing any additional actions।