I have an array of objects named Employees and am trying to get the ones who are department_id=3 and I don't want to go back to laravel and make another request so is there a way to do so with vuex?
"id": 25,
"name": "name",
"email": "[email protected]",
"last_name": "lastname",
"phone": "98745632",
"gender": "Male",
"nationality": "Tunisian",
"school": "ISIMM",
"experience_level": "2",
"source": "Linkedin",
"hiring_date": "2020-04-17",
"end_contract": "2020-04-18",
"position": "web developer",
"grade": "Junior",
"contract": "Cdi",
"department_id": 1,
"company_id": 1,
"archived": "0",
"img": null,
"supervisor_id": 1,
"ipAdress": null,
"last_login_at": null,
"department": {
"id": 1,
"name": "mobile"
},
here's state :
const employee = {
state: {
Employees: [],
sysAdmins: [],
},
here's getters :
sysAdmins: (state) =>
state.Employees.map((element) => (element.department_id = "3")),
Employees: (state) => state.Employees,
here's mutations :
getsysAdmins(state, employees) {
state.sysAdmins = employees;
},
getEmployees(state, employees) {
state.Employees = employees;
},
here's
actions :
getEmployees(context) {
const config = {
headers: {
"x-api-key": process.env.VUE_APP_SIRH_X_API_KEY,
Authorization: localStorage.getItem("access_token"),
},
};
return new Promise((resolve, reject) => {
axios
.get("/employees/all_employees", config)
.then((response) => {
context.commit("getEmployees", response.data.data.users);
context.commit("getsysAdmins", response.data.data.users);
resolve(response);
})
.catch((error) => {
reject(error);
});
});
},
If I understand it right, you want to return the while Employee Object for those employees that work in a certain department. You can do this by filtering your Employees array. I would write that as following:
getters: {
employees: (state) => state.Employees,
sysAdmins: (state) => state.Employees.filter((employee) => employee.department_id === 3),
// If your DB returns a string as the department_id, you'll have to check against "3"
}
If sysAdmins is always a subset of the employees, it makes more sense to always use a getter instead of placing these in a separate array in the state.
Some other notes:
- You mutations are called get...
while these are setters, it might be best to rename these.
- In your action, you currently set the same result as employees and sysAdmins. Again, I would just set employees and always filter the sysAdmins from that array.