Reputation: 649
I am new to Redux and trying to use Redux in my React App.
Here are my Reducers.
The roor reducer -
import {combineReducers} from 'redux';
import dataListReducer from './dataList';
export default combineReducers({
dataListReducer
})
and dataList reducer-
const INITITAL_STATE={gridData:[]}
const dataListReducer=(state=INITITAL_STATE,action)=>{
switch(action.type){
default: return {...state}
}
return state;
}
export default dataListReducer;
Here is the action creator class -
export const dataLoaded=(data)=>{
return {
type:'full_data',
payload:{gridData:data}
}
}
Now from the below component I am making a Fetch call to the network and when the call returns I want to update the application state with the latest data -
componentDidMount()
{
FetchService(this.state.url)
.then((res)=> res.json())
.then( (result)=>this.updateState(result)
).catch(function(error){console.log(error)});
}
updateState(result)
{
this.props.dataLoaded(result);
}
The component is making a call to connect as prescribed -
const mapStateToProps=(state)=>{
console.log(state);
return state;
}
export default connect(mapStateToProps,{dataLoaded})(Main)
Why does the console.log does not print the latest data?
What am I missing here?
Please let me know if I can clarify further.
Upvotes: 0
Views: 55
Reputation: 581
This should work for you.
const INITITAL_STATE={gridData:[]}
const dataListReducer=(state=INITITAL_STATE,action)=>{
switch(action.type){
case: 'full_data':
return { ...state, gridData: action.payload.gridData }
default: return {...state}
}
}
export default dataListReducer;
Upvotes: 1
Reputation: 1564
What you've done in your reducer is to return the same state it already has. So it's a void reducer - like doing no action. What you need to do is when returning from the reducer, to actually take into account what is passed in action's payload.
case "full_data":
return { ...state, action.payload }
or I would even suggest to specify explicitly the property, so that further extensions will be possible and will not override any siblings
case "full_data":
return { ...state, ...gridData: action.payload.gridData }
Upvotes: 1
Reputation: 15698
Friend, you have not defined anything in your reducer to process actions that are dispatched to it.
To do that you need to set up some cases in your reducer like this:
const dataListReducer=(state=INITITAL_STATE,action)=>{
switch(action.type){
case "full_data":
return {...state, myData}
default:
return state
}
That way your reducer will update when an action is dispatched to it.
Upvotes: 1