Three ways to handle data fetching logic in React projects!
Friday 17 December 2021 06:18 PM Beirut Time · 256
Wajdi Alkayal Wajdi Alkayal
Three ways to handle data fetching logic in React projects!

The Simplest Way


import { useEffect, useState } from 'react';
const ReactWay = () => {
  const [apiData, setApiData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/todos'
      );
      const data = await response.json();
      setApiData(data);
      setIsLoading(false);
    };

    fetchData().catch((e) => setError(e.message));
  }, []);

  return (
    <div>
      <h1>React Way</h1>
      {error ? (
        <>Oh no, there was an error</>
      ) : isLoading ? (
        <>Loading...</>
      ) : apiData ? (
        <>
          <ul>
            {apiData.map((item) => (
              <li key={item.id}>{item.title}</li>
            ))}
          </ul>
        </>
      ) : null}
    </div>
  );
};

	export default ReactWay;

The Redux Way

npm install @reduxjs/toolkit react-redux
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const todoApi = createApi({
	reducerPath: 'todoApi',
	baseQuery: fetchBaseQuery({
		baseUrl: 'https://jsonplaceholder.typicode.com/',
	}),
	endpoints: (builder) => ({
		getTodos: builder.query({
			query: () => 'todos',
		}),
	}),
});

export const { useGetTodosQuery } = todoApi;

You can already see how you can set up all your endpoints at one place. Next all you have to do is set up your store. Do remember to export the auto-generated hooks as I did, this is how the RTK Query docs want you to do.

import { configureStore } from '@reduxjs/toolkit';
import { todoApi } from './services/todo';

export const store = configureStore({
	reducer: {
		[todoApi.reducerPath]: todoApi.reducer,
	},
	middleware: (getDefaultMiddleware) =>
		getDefaultMiddleware().concat(todoApi.middleware),
});
The middleware is optional but provides additional features as stated in the comments. All that is left is to provide the store to your app.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './store';

import App from './App';

ReactDOM.render(
	<Provider store={store}>
		<App />
	</Provider>,
	document.getElementById('root')
);

import { useGetTodosQuery } from '../services/todo';

const ReduxWay = () => {
	const { data, error, isLoading } = useGetTodosQuery();
	return (
		<div>
			<h1>Redux Way</h1>
			{error ? (
				<>Oh no, there was an error</>
			) : isLoading ? (
				<>Loading...</>
			) : data ? (
				<>
					<ul>
						{data.map((item) => (
							<li key={item.id}>{item.title}</li>
						))}
					</ul>
				</>
			) : null}
		</div>
	);
};

export default ReduxWay;

The React Query Way

npm install react-query
import ReactQueryWay from './components/ReactQueryWay';

import { QueryClient, QueryClientProvider } from 'react-query';
const queryClient = new QueryClient();

const App = () => {
	return (
		<>
			<QueryClientProvider client={queryClient}>
				<ReactQueryWay />
			</QueryClientProvider>
		</>
	);
};

export default App;

So, which is the best way?

Related Posts
Graphic design
09 June
The Power of Email Marketing
03 June
Photography
01 June