03_lesson: dispatch fetching users at beginning of loading
parent
e8dedad084
commit
14c4682dcf
|
@ -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
|
||||||
|
|
|
@ -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>
|
||||||
|
|
Loading…
Reference in New Issue