📚

Fetching Data with Redux Toolkit

Aug 29, 2024

Fetching Data with Redux Toolkit

Introduction

  • This video tutorial focuses on fetching data from an API using Redux Toolkit in a React application.

Setup

  1. Create React App
    • A new React application is created as the starting point.
  2. Install Dependencies
    • Use the terminal to install the necessary libraries: npm install react-redux @reduxjs/toolkit

Create Redux Structure

Create Folder

  • Inside the src folder, create a new folder named redux.

Create Store

  1. File Creation
    • Create a file named store.jsx in the redux folder.
  2. Import configureStore
    • Import configureStore from @reduxjs/toolkit.
  3. Store Setup
    • Initialize the store with a slice for todos: const store = configureStore({ reducer: { todo: todoSlice.reducer } });
  4. Export Store
    • Export the created store for use in the application.

Create Todo Slice

  1. File Creation
    • Create a file named todoSlice.jsx in the redux folder.
  2. Import Required Methods
    • Import createSlice and createAsyncThunk from @reduxjs/toolkit.
  3. Initial State
    • Define the initial state with three properties: isLoading, data, and error.
  4. Create Slice
    • Use createSlice to define the slice with reducers and asynchronous actions: const todoSlice = createSlice({ name: 'todo', initialState: { isLoading: false, data: [], error: false }, reducers: {}, });
  5. Create Async Thunk
    • Define an async thunk to fetch todos: export const fetchTodo = createAsyncThunk('todo/fetchTodos', async () => { const response = await fetch('API_URL_HERE'); return response.json(); });
  6. Handle Async States
    • Handle different states (pending, fulfilled, rejected) in the extra reducers.

Integrate Redux Store into App

  1. Provider Setup
    • In main.jsx, wrap the application with Provider and pass the store: import { Provider } from 'react-redux'; import store from './redux/store'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );

Create Todo Component

  1. File Creation
    • Create a new component named Todo.jsx.
  2. Import Hooks
    • Import useDispatch and useSelector hooks from react-redux.
  3. Dispatch Fetch Action
    • Use useEffect to dispatch the fetchTodo action: useEffect(() => { dispatch(fetchTodo()); }, [dispatch]);
  4. Render Data
    • Display loading text or fetched todos using conditional rendering based on loading state: if (isLoading) { return <h1>Loading...</h1>; } else { return data.map(todo => <p key={todo.id}>{todo.title}</p>); }

Conclusion

  • The video concludes by summarizing the setup and implementation of fetching data using Redux Toolkit.
  • Encourages viewers to subscribe and like the video if it was helpful.