Files
biblio/assets/js/store/modules/books.js

72 lines
1.9 KiB
JavaScript

import BookApi from "../../api/book";
const
FETCHING_BOOKS = "FETCHING_BOOKS",
FETCHING_BOOKS_SUCCESS = "FETCHING_BOOKS_SUCCESS",
FETCHING_BOOKS_ERROR = "FETCHING_BOOKS_ERROR",
SETTING_SEARCH_TERM = "SETTING_SEARCH_TERM"
;
export default {
namespaced: true,
state: {
isLoading: false,
error: null,
books: [],
searchTitle: null
},
getters: {
isLoading(state) {
return state.isLoading;
},
hasError(state) {
return state.error !== null;
},
error(state) {
return state.error;
},
hasBooks(state) {
return state.books.length > 0;
},
books(state) {
return state.books;
},
isSearching(state) {
return !!state.searchTitle;
}
},
mutations: {
[SETTING_SEARCH_TERM](state, searchTitle) {
state.searchTitle = searchTitle;
},
[FETCHING_BOOKS](state) {
state.isLoading = true;
state.error = null;
state.books = [];
},
[FETCHING_BOOKS_SUCCESS](state, books) {
state.isLoading = false;
state.error = null;
state.books = books;
},
[FETCHING_BOOKS_ERROR](state, error) {
state.isLoading = false;
state.error = error;
state.books = [];
}
},
actions: {
async findAll({commit, state}, searchTitle) {
commit(FETCHING_BOOKS);
try {
commit(SETTING_SEARCH_TERM, searchTitle);
let response = await BookApi.booksFetch(state.searchTitle);
commit(FETCHING_BOOKS_SUCCESS, response.data);
return response.data;
} catch (error) {
commit(FETCHING_BOOKS_ERROR, error);
return null;
}
}
}
};