From 14c4682dcfaf3a6f53c061cf7f696ee4a43d80e7 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Tue, 7 Mar 2023 22:25:52 +1100 Subject: [PATCH] 03_lesson: dispatch fetching users at beginning of loading --- .../src/features/users/usersSlice.js | 28 ++++++++++++++----- 02_lesson_starter/src/index.js | 3 ++ 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/02_lesson_starter/src/features/users/usersSlice.js b/02_lesson_starter/src/features/users/usersSlice.js index 9adef65..907836a 100644 --- a/02_lesson_starter/src/features/users/usersSlice.js +++ b/02_lesson_starter/src/features/users/usersSlice.js @@ -1,14 +1,28 @@ -import { createSlice } from "@reduxjs/toolkit"; -const initialState = [ - { id: "0", name: "Dude Lebowski" }, - { id: "1", name: "Neil Young" }, - { id: "2", name: "Dave Gray" }, -]; +import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; +import axios from 'axios'; + +const USERS_URL = 'https://jsonplaceholder.typicode.com/users'; + +const initialState = []; + +export const fetchUsers = createAsyncThunk('users/fetchUsers', async () => { + try { + const response = await axios.get(USERS_URL); + return [...response.data]; + } catch (err) { + return err.message; + } +}); const usersSlice = createSlice({ - name: "users", + name: 'users', initialState, reducers: {}, + extraReducers(builder) { + builder.addCase(fetchUsers.fulfilled, (state, action) => { + return action.payload; + }); + }, }); // Selectors diff --git a/02_lesson_starter/src/index.js b/02_lesson_starter/src/index.js index b2adf95..73463a0 100644 --- a/02_lesson_starter/src/index.js +++ b/02_lesson_starter/src/index.js @@ -4,6 +4,9 @@ import './index.css'; import App from './App'; import { store } from './app/store'; import { Provider } from 'react-redux'; +import { fetchUsers } from './features/users/usersSlice'; + +store.dispatch(fetchUsers()); // Fetch users before rendering page ReactDOM.render(