I am working on an app, written in React.js, where I get data from a JSON feed and then I'll use this data in various ways in the app.
I make the call to the feed via axios:
module.exports = { getMainPlaylist: function () { var requestUrl = `${MAIN_PLAYLIST_FEED_URL}`; return axios.get(requestUrl).then(function (res) { return res.data.playlist }, function (err) { alert('error'); }); } };
In my app.jsx file, I have the following:
store.subscribe(() => { var state = store.getState(); console.log('New state: ', state); }); var mainPlaylist = MainPlaylistAPI.getMainPlaylist(); store.dispatch(actions.addMainPlaylist(mainPlaylist));
In my actions file, I have this:
export var addMainPlaylist = (mainPlaylist) => { return { type: 'ADD_MAIN_PLAYLIST', mainPlaylist } };
In my reducers file I have this:
export var playlistReducer = (state = [], action) => { switch (action.type) { case 'ADD_MAIN_PLAYLIST': return [ ...state, ...action.mainPlaylist ]; default: return state; } };
When I was using the state as normal to get the data it was working fine but I think because I'm trying to use the store with a web service it's probably not working because of the asynchronous process.
When I log to the console I get this:
I come from a .NET background so I'm fairly new to working only in JavaScript and I have no idea where to start to fix this.
Any help is appreciated!
I managed to solve this myself.
Axios is a promise-based client so I used .then() where I call it.
So this:
var mainPlaylist = MainPlaylistAPI.getMainPlaylist(); store.dispatch(actions.addMainPlaylist(mainPlaylist));
Become this:
MainPlaylistAPI.getMainPlaylist().then(function (data) { store.dispatch(actions.addMainPlaylist(data)); }, function(e) { // Handle errors });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.