mirror of
https://github.com/bluewave-labs/Checkmate.git
synced 2026-01-23 18:19:51 -06:00
Refactored to use thunk for Axios request
This commit is contained in:
@@ -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;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user