Search code examples
javascriptreactjsreduxreact-reduxredux-toolkit

Redux toolkit: call function after updating state


I have the logic. The user clicks on the button, then the answer changes and is compared with the correct answer.

The problem is that after dispatching, I have a previous version of the state when I try to compare.

What I'm trying to do:

Check.jsx:

const Check = () => {
  const {answer, userAnswer} = useSelector(state => state.check);
  const currentAnswer = 'current'

  // here is the main problem, the userAnswer is in the previous state
  const check = () => {
    if(answer === userAnswer){
     // some other stuff
    }
  }
 
  return(
    <div>
     //something else 
     <Button userAnswer={currentAnswer} check={check} />
   </div>
  )
}

Button.jsx:

const Button = (userAnswer, check) => {
 const dispatch = useDispatch();

  return(
    <button onClick={() => {
      dispatch(updateAnswer(userAnswer)).then(() => check())
    }}>
      Check answer
    </button>
  )
}

checkSlice.js:

export const updateAnswer = createAsyncThunk('surplus/getAllUsers', async (word: string) => {
    return word;
});

const initialState = {
  userAnswer: '',
  answer: 'some string'
}

const checkSlice = createSlice({
    name: 'check',
    initialState,
    reducers: {
    },
    extraReducers(builder) {
        builder.addCase(updateAnswer.fulfilled, (state, action) => {
            state.userAnswer = action.payload;
        });
    },
});


Solution

  • Please do comparison in reducers like

    export const updateAnswer = createAsyncThunk('surplus/getAllUsers', async (word: string) => {
        return word;
    });
    
    const initialState = {
      userAnswer: '',
      check: false
      answer: 'some string'
    }
    
    const checkSlice = createSlice({
        name: 'check',
        initialState,
        reducers: {
        },
        extraReducers(builder) {
            builder.addCase(updateAnswer.fulfilled, (state, action) => {
                if(state.userAnswer === action.payload){
                   state.check = true;
                   state.userAnswer = action.payload;
                  } else {
                   state.check = false;
                  }
            });
        },
    });
    

    You can get check variable from redux and then perform action using useEffect on check like

    useEffect(()=>{
    // some other stuff
    },[check]) // check from redux