Added async thunk for creating monitors, connected CreateMonitor to backend

This commit is contained in:
Alex Holliday committed 2024-06-27 15:27:32 -07:00
1 parent fd8a0d455c
commit 7a066733da
2 files changed
+58 -9

No files matched your search

@@ -1,6 +1,7 @@
import axios from "axios";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { jwtDecode } from "jwt-decode";
const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;
const initialState = {
isLoading: false,
@@ -9,6 +10,28 @@ const initialState = {
msg: null,
};
export const createMonitor = createAsyncThunk(
"monitors/createMonitor",
async (data, thunkApi) => {
try {
const { authToken, monitor } = data;
const res = await axios.post(`${BASE_URL}/monitors`, monitor, {
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
return res.data;
} catch (error) {
if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data);
}
return thunkApi.rejectWithValue(error.message);
}
}
);
export const getMonitors = createAsyncThunk(
"monitors/getMonitors",
async (token, thunkApi) => {
@@ -99,6 +122,25 @@ const monitorsSlice = createSlice({
state.msg = action.payload
? action.payload.msg
: "Getting montiors failed";
})
// *****************************************************
// Create Monitor
// *****************************************************
.addCase(createMonitor.pending, (state) => {
state.isLoading = true;
})
.addCase(createMonitor.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
})
.addCase(createMonitor.rejected, (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? action.payload.msg
: "Failed to create monitor";
});
},
});