Q
Q
qfrontend2020-07-23 15:57:42
React
qfrontend, 2020-07-23 15:57:42

Why dispatch is not a function?

Why dispatch is not a function?
app.js

import React, { useEffect } from "react";
import { connect } from "react-redux";

import fetchWorkers from "../actions/workers/fetchWorkers";

import "./App.css";

function App() {
  useEffect(() => {
    fetchWorkers();
  });
  return <div className="App"></div>;
}

const mapStateToProps = (store) => {
  return {
    workers: store.workers,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    fetchWorkers: () => dispatch(fetchWorkers()),
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(App);

fetchWorkers.js
export const FETCH_WORKERS_REQ = "FETCH_WORKERS_REQ";
export const FETCH_WORKERS_SUCC = "FETCH_WORKERS_SUCC";

const fetchWorkers = () => {
  console.log(1); /*Здесь консоль отрабатывает*/
  return (dispatch) => {
    console.log(2); /*А вот здесь уже НЕТ*/
    dispatch({
      type: FETCH_WORKERS_REQ,
      payload: {
        wait: true,
        workers: [],
      },
    });

    setTimeout(() => {
      dispatch({
        type: FETCH_WORKERS_SUCC,
        payload: {
          wait: false,
          workers: ["Jon", "Sam", "Lina"],
        },
      });
    }, 1000);
  };
};

export default fetchWorkers;

export default fetchWorkers;

store.js
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import reducer from "../reducers/rootR";
import thunk from "redux-thunk";

export const store = createStore(
  reducer,
  composeWithDevTools(applyMiddleware(thunk))
);

rootR.js
import { combineReducers } from "redux";
import workersR from "./workers/workersR";

const rootR = combineReducers({
  workers: workersR,
});
export default rootR;

workersR.js
import { FETCH_WORKERS_REQ } from "../../actions/workers/fetchWorkers";

const initialState = {
  wait: true,
  workers: [],
};

const workersR = (state = initialState, action) => {
  switch (action.type) {
    case FETCH_WORKERS_REQ:
      return {
        ...state,
        wait: action.payload.wait,
      };
    default:
      return state;
  }
};

export default workersR;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vadimparinov, 2020-07-23
@vadimparinov

const fetchWorkers = (url) => {
         return {
             type:FETCH_WORKERS_REQ,
             payload:{wait:true}
         }
};

Because that's how it should be. Better read the documentation
https://redux.js.org/basics/actions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question