Setting up Vuex module to manage news data from the API
We set up new folders and files for managing the stores and the routes out.
Let us use the news current-news.js file and example and go through the code to explain certain concepts.
In the src folder, we create a new folder called constants and two files for general API constants and mutations in our applications.
We do the usual imports of necessary actions and mutations types, API constants such as the URL that points to the express JS server we created previously.
Next, we will create an object with two properties, newsArticles and newsError to keep the state of news items. The newsArticles property will contain the news items we retrieved from the API and newsError will contain the error object if our API call fails.
import * as appConstant from "../../constants/appConstants";
import * as types from "../../constants/mutation-types";
const state = {
newsArticles: {},
newsError: {}
};
We use the inbuilt fetch functionality to make networks request to our express API. In the case of a successful API call, we commit our data to the store using the mutation type GET_NEWS_DATA_SUCCESS and in case an error is thrown we commit it as a failure of mutation type GET_NEWS_DATA_FAILURE .
Since we going to use the news data for different pages of our application, we need to build a getter function to easily access the piece of state that the component/view needs to retrieve from the store. We pass the particular category of news items that we want to retrieve from the store and return that particular category from state objectnewsArticles
Next, we set up our mutation handlers. As seen previously in our actions function, we have two mutation types that can commit changes to our data. How these types mutate / change data is handled in the mutation handlers below. In the case of mutation type GET_NEWS_DATA_FAILURE we simply assign the error object retrieved to the newsError state we previously created.
In the case of GET_NEWS_DATA_SUCCESS we use the category of data retrieved as key in our state object and then assign the articles retrieved from the API for that particular category to it.