1

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

Kostya Tresko
  • 754
  • 1
  • 5
  • 24
  • Does this answer your question? https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Lin Du Oct 12 '21 at 11:45

1 Answers1

0

It's working fine, I have added a button to call increment() method once clicked on, I think you thought it's not working cause the call to increment method exists in the useEffect method that will trigger once the component loaded "without dependencies"

For your sandbox, try to change things in code to re-render the Counter component and you will see the counter incrementing

Your SandBox Fork

Obaida Alhassan
  • 516
  • 1
  • 5
  • 12