Refactored to use thunk for Axios request

This commit is contained in:
Alex Holliday
2024-06-04 13:32:17 -07:00
parent fbe357091a
commit 9926f60c09
2 changed files with 35 additions and 18 deletions

View File

@@ -1,4 +1,5 @@
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
const initialState = {
isLoading: false,
@@ -7,13 +8,39 @@ const initialState = {
msg: null,
};
export const getMonitors = createAsyncThunk(
"monitors/getMonitors",
async (token, thunkApi) => {
try {
const res = await axios.get("http://localhost:5000/api/v1/monitors");
return res.data;
} catch (error) {
return thunkApi.rejectWithValue(error.response.data);
}
}
);
const monitorsSlice = createSlice({
name: "monitors",
initialState,
reducers: {
setMonitors: (state, action) => {
state.monitors = action.payload;
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(getMonitors.pending, (state, action) => {
state.isLoading = true;
})
.addCase(getMonitors.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
console.log(action.payload);
state.monitors = action.payload.data;
})
.addCase(getMonitors.rejected, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
});
},
});

View File

@@ -30,7 +30,7 @@ import Divider from "@mui/material/Divider";
// Redux
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { setMonitors } from "../../Features/Monitors/monitorsSlice";
import { getMonitors } from "../../Features/Monitors/monitorsSlice";
const cols = [
{
@@ -211,18 +211,8 @@ const Demo = () => {
<Button
level="primary"
label="Get Monitors"
onClick={async () => {
try {
const response = await axios.get(
"http://localhost:5000/api/v1/monitors"
);
const monitorsResponse = response.data;
const monitors = monitorsResponse.data;
console.log(monitors);
dispatch(setMonitors(monitors));
} catch (error) {
console.log(error);
}
onClick={() => {
dispatch(getMonitors());
}}
/>
</div>