Reputation: 834
I'm new to Redux and I think I'm starting to understand how it all works, but I'm having initial problems getting data into the Store.
I believe I'm close, but there's just something that I'm not getting. Any help is appreciated!
The reason I need this to work is because I have other components that will work with the same data, so I figured it's best to keep the data in the Redux Store. If there are other ways to solve this, please enlighten me.
Action:
import fetch from "isomorphic-fetch";
export const LOAD_DATA = "LOAD_DATA";
function getApiUrl() {
return `${window.appDefaultState.url.baseUrl}/api`;
}
export function loadStoresData() {
return function(dispatch) {
dispatch({
type: LOAD_DATA,
stores: data
});
fetch(
getApiUrl(),
{
method: "post",
credentials: 'same-origin',
body: JSON.stringify({
form_key: window.appDefaultState.formKey,
"cms/stores": 1
})
}
)
.then(response => response.json())
.then(json => {
console.log("fetched data in actions")
let data = json["cms/stores"];
console.log(data);
dispatch({
type: LOAD_DATA,
stores: data
});
})
.catch(e => {
console.log(e)
});
}
}
function getSuccess(data) {
console.log("getSuccess worked")
return (
type: LOAD_DATA,
stores: data
)
}
Reducer:
import {
LOAD_DATA
} from "actions/storelist.js";
function initialState() {
return Object.assign({}, {
stores: {},
}, window.appDefaultState.storeList);
}
export default function storeList(state, action) {
if (!state) {
state = initialState();
}
switch (action.type) {
case LOAD_DATA:
return Object.assign({}, state, {
stores: action.data
});
break;
}
return state;
}
Component (relevant parts):
import { connect } from "react-redux";
import { loadStoresData } from "actions/storelist.js";
const actions = {
loadStoresData
}
const mapStateToProps = (state, ownProps) => {
return Object.assign({
stores: state.stores
}, ownProps);
};
export default connect(mapStateToProps, actions)(StorePage);
Upvotes: 0
Views: 47
Reputation: 7734
You dispatch data
in stores
field, so it should be
switch (action.type) {
case LOAD_DATA:
return Object.assign({}, state, {
stores: action.stores
});
}
Replace action.data
with action.stores
Upvotes: 1