This is my reducer.js
const initialState = {
counter: 0
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'increase':
state = { ...state, counter: state.counter + 1 }
break
default:
break
}
return state
}
export default reducer
This is my index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'
import reducer from './reducer'
const store = createStore(reducer, applyMiddleware(thunk))
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root'))
This is my code in React App.js
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
function App() {
const dispatch = useDispatch()
const counter = useSelector(state => state.counter)
const increment = (dispatch) => {
return function () {
return Promise.resolve(dispatch({ type: 'increase' }))
}
}
const myFunc = increment(dispatch)
const onClickIncrease = async () => {
console.log('Before dispatch:', counter)
myFunc().then(() => {
console.log('After dispatch:', counter) *** // Why this line prints the same value as Before dispatch ***
})
}
return (
<div>
<button onClick={onClickIncrease}>
+
</button>
</div>
)
}
export default App
When I clicked the +
button three times, I saw:
Before dispatch: 0
After dispatch: 0
Before dispatch: 1
After dispatch: 1
Before dispatch: 2
After dispatch: 2
I don't understand why the counter printed in Before and After are the same. Can anyone suggest what should I do if I want to see something like this:
Before dispatch: 0
After dispatch: 1
Before dispatch: 1
After dispatch: 2
Before dispatch: 2
After dispatch: 3