Reputation: 1672
Working with a React based app with Redux for state, and I have a component that is supposed to load up a list of data from the back end on load.
I have the component loading, with state and actions mapped. I have the main data call for the component here:
componentWillMount(){
this.props.loadTasks(this.props.user);
}
which fires the action function here:
export const loadTaskList = (user) => {
return (dispatch) => {
fetch(`http://localhost:3201/tasks/${user._id}`)
.then(res => res.json())
.then(tasks => {
console.dir(tasks);
return({type: LOAD_TASKS, payload: tasks});
});
}
}
which gets sent to the reducer, and incorporated into the store like this:
export default (state=initState, {type, payload}) => {
switch (type) {
case LOAD_TASKS:
console.log(`Payload of tasks: ${payload}`);
return{...state, tasks: payload};
default:
return state;
}
}
The question is why this isn't getting into my state, and therefore in my component?
Edit: just for clarity, my mapState, and mapActions objects:
let mapState = (state) => ({
tasks: state.tasklist,
user: state.user
});
let mapActions = (dispatch) => ({
loadTasks: loadTaskList, //taskList Reducer
selectTask: selectTask, //ActiveTask Reducer
deleteTask: deleteTask, //TaskList Reducer
newTask: newTask //activeTask Reducer
});
Upvotes: 1
Views: 655
Reputation: 104389
Because you are not dispatching the action
, use this:
dispatch({type: LOAD_TASKS, payload: tasks});
Instead of:
return({type: LOAD_TASKS, payload: tasks});
Return will not do anything.
Upvotes: 1
Reputation: 464
UNSAFE_componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead for initializing state.
I would recommend the same or call loadTasks() in componentDidMount() {} instead of componentWillMount()
Upvotes: 0