Z
Z
zlodiak2020-11-04 01:06:07
React
zlodiak, 2020-11-04 01:06:07

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/>
  );
}


The corresponding thunk is stored in the reducer file:
todoReducers.js:
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));
        });
    }
}


As you can see, there are two 'debugger' instructions in this thunk. The problem is that the script execution flow reaches the first debugger, but not the second one. Accordingly, thunk does not fulfill its task.

Full code on github

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Zhivagin, 2020-11-04
@zlodiak

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);

Or use the useDispatch hook, you can google about this method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question