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";
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

View File

@ -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(
<React.StrictMode>