I'm building a tool using React and Redux. I'm using whatwg-fetch to make a server side call and fetch some data. And I have a reducer, which will have its store created in a callback, after the data has been successfully fetched. Here is my code:
import {createStore} from 'redux';
import 'whatwg-fetch';
let notificationCardList = [],
initialState,
store;
const fetchData = () => {
fetch('http://localhost:6767/file/data.json')
.then((response) => response.json())
.then((responseData) => {
notificationCardList = Object.keys(responseData).map(key => responseData[key]);
})
.then(initializeReducer);
}
const initializeReducer = () => {
initialState = {
notifCardsToBeDisplayed: notificationCardList,
notifCardToBeDisplayed: null
};
function manipulateNotificationCards (state = initialState, action) {
switch (action.type) {
case 'OPEN_CARD':
return Object.assign(state, {
notifCardsToBeDisplayed: null,
notifCardToBeDisplayed: action.card,
notifCardsContainerPreviousState: action.notifCardsContainerCurrentState
});
case 'DISPLAY_CARD_LIST':
return Object.assign(state, {
notifCardsToBeDisplayed: action.cards,
notifCardToBeDisplayed: null
});
default:
return state;
}
}
store = createStore(manipulateNotificationCards);
}
fetchData();
export {store, notificationCardList};
But since the store is being created as a part of the callback, due to asynchronous behaviour, the export statement is probably getting executed before the createStore() statement, hence I'm effectively exporting an undefined 'store'. I thought about placing the export statement in the callback as well, but then again, export statements can only be there at the top level. I also tried using setTimeout(), but that didn't work either. Is there any way I can export 'store' after it's created?