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(