I'm using redux toolkit createSlice:
export const counter = createSlice({
...
reducers: {
increment: (state, action) => state + 1,
...
}
});
export const { increment } = counter.actions;
Using in component:
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { increment as _increment } from "../slices/counter";
const Counter = ({ counter, increment }) => {
useEffect(() => {
console.log(counter); // Let's assume that counter=k
increment();
console.log(counter); // I think that here counter should be equal k+1, but it still is k as if increment is async
}, []);
return <div>Counter: {counter}</div>;
};
const mapStateToProps = (state) => ({
counter: state.counter
});
const mapDispatchToProps = {
increment: _increment
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
I expect increment function to be sync so that on the next line after executing it redux store will be changed. In my example I expect first console.log to return k
and second k+1
. Why does this happen. Is there way to wait until store changes?
Here is sandbox