03_lesson: dispatch fetching users at beginning of loading

03_lesson
Jason Zhu 2023-03-07 22:25:52 +11:00
parent e8dedad084
commit 14c4682dcf
2 changed files with 24 additions and 7 deletions

View File

@ -1,14 +1,28 @@
import { createSlice } from "@reduxjs/toolkit"; import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
const initialState = [ import axios from 'axios';
{ id: "0", name: "Dude Lebowski" },
{ id: "1", name: "Neil Young" }, const USERS_URL = 'https://jsonplaceholder.typicode.com/users';
{ id: "2", name: "Dave Gray" },
]; 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({ const usersSlice = createSlice({
name: "users", name: 'users',
initialState, initialState,
reducers: {}, reducers: {},
extraReducers(builder) {
builder.addCase(fetchUsers.fulfilled, (state, action) => {
return action.payload;
});
},
}); });
// Selectors // Selectors

View File

@ -4,6 +4,9 @@ import './index.css';
import App from './App'; import App from './App';
import { store } from './app/store'; import { store } from './app/store';
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import { fetchUsers } from './features/users/usersSlice';
store.dispatch(fetchUsers()); // Fetch users before rendering page
ReactDOM.render( ReactDOM.render(
<React.StrictMode> <React.StrictMode>