ibms-dome/ibms_react/src/stores/buildingSlice.js

48 lines
1.4 KiB
JavaScript

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { deviceBuiListBaseUrl } from "@CON";
import { ajaxRes } from "@UTIL";
// 異步取得區域及棟別
export const fetchBuiList = createAsyncThunk("building/fetchBuiList", async (token, thunkAPI) => {
const res = await axios.post(deviceBuiListBaseUrl);
const { building_tag, urn_3D, full_name } = res.data[0];
thunkAPI.dispatch(changeBuilding({ building_tag, urn_3D, full_name }));
return ajaxRes(res, thunkAPI);
});
const buildingSlice = createSlice({
name: "building",
initialState: {
buildingList: ["中凌大樓"],
urn_3D: "",
selectedBuiArea: "TPE",
selectedBuiTag: "B1",
selectedBuiFullName: "",
errMsg: "",
},
reducers: {
// 改變區域
changeArea: () => {},
// 改變棟別
changeBuilding: (state, { payload: { building_tag, urn_3D, full_name } }) => {
state.urn_3D = urn_3D;
state.selectedBuiTag = building_tag;
state.selectedBuiFullName = full_name;
},
},
extraReducers: (builder) => {
// pending, fulfilled, rejected
builder
.addCase(fetchBuiList.fulfilled, (state, { payload }) => {
state.buildingList = payload;
})
.addCase(fetchBuiList.rejected, (state, { payload }) => {
state.errMsg = payload;
});
},
});
const { actions, reducer } = buildingSlice;
export const { changeBuilding } = actions;
export default reducer;