Refactored to use thunk for Axios request
This commit is contained in:
1 parent
fbe357091a
commit
9926f60c09
2 files changed
+35
-18
No files matched your search
@@ -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;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user