J
J
justifycontent2021-06-17 09:44:44
React
justifycontent, 2021-06-17 09:44:44

Why does dispatch need to be used 2 times?

App.js component

const App = () => {
  const dispatch = useDispatch();

  React.useEffect(() => {
// Вот тут я диспатчу fetchPizzas, но зачем? Если fetchPizzas это делает внутри себя.
    dispatch(fetchPizzas())
  }, [])


  return (
    <div className="wrapper">
      <Header />  {/*--------H E A D E R-------*/}
      <div className="content">
        <Route exact path='/' component={Home} /> {/*--------H O M E-------*/}
        <Route exact path='/cart' component={Cart} /> {/*--------C A R T-------*/}
      </div>
    </div>
  )
}

export default App;


actions:
import axios from 'axios'

const fetchPizzas = () => (dispatch) => {
  axios.get('http://localhost:3003/pizzas').then(({ data }) => {
    dispatch(setPizzas(data))
  })
}

const setPizzas = items => ({
  type: 'SET_PIZZAS',
  payload: items,
});

export default fetchPizzas

Why is it not enough to just call fetchPizzas()? Executing this query using redux-thunk

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2021-06-17
@justifycontent

You have two actions:

  1. Run a query
  2. Save the result

Therefore, there are two dispatch.

X
xirurgx3d, 2021-06-17
@xirurgx3d

redux-thunk is a middleware that implies an intermediate layer between your action and reduser,
in which you can hang as many dispatchers as you like on one action reaction fetchPizzas
is a partial application function where you can pass the parameters you need, and redux-thunk , already passes dispatch to the nested function, so that you can inside your three functions, you can call other actions through dispatch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question