Answer the question
In order to leave comments, you need to log in
Why doesn't thunk work?
Please help me understand why thunk does not work. In the component, I call thunk, which should initialize the store with the actual values from the database. As a database, I temporarily use http-server (this is an imitation of the backend)
App.js:
import { addTodoCreator, initTodosThunk } from './redux/todosReducer';
function App() {
initTodosThunk();
return (
<Header/>
);
}
const todosReducer = function todosReducer(state = { todos: [] }, action) {
switch(action.type) {
case 'ADD_TODO': {
state = {
...state,
todos: [ ...state.todos, action.payload ],
};
break;
}
default:
return state;
}
return state;
}
export const addTodoCreator = todo => {
return { type: 'ADD_TODO', payload: todo }
}
export const initTodosThunk = () => {
debugger // ДОХОДИТ
return async dispatch => {
debugger // НЕ ДОХОДИТ
const response = await fetch(`${API_URL}/todos`);
const todos = await response.json();
todos.forEach(todo => {
dispatch(addTodoCreator(todo));
});
}
}
Answer the question
In order to leave comments, you need to log in
The problem is that you are calling the function in the standard way. It returns you a second function (with a second debugger) that you don't call anywhere. You won’t be able to in this way, since you need to somehow throw dispatch into it.
You have to connect (from react-redux) the App component, something like this:
import { connect } from 'react-redux';
// ...
const mapDispatchToProps = {
callInitTodosThunk: initTodosThunk
}
// ...
function App(props) {
const { initTodosThunk } = props
callInitTodosThunk();
return (
<Header/>
);
}
export default connect(null, mapDispatchToProps)(App);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question