0

I have a simple app using react-native and redux:

import { createReducer, createActions } from 'reduxsauce';
import Immutable from 'seamless-immutable';

/* ------------- Types and Action Creators ------------- */

const { Types, Creators } = createActions({
  setAnswer: ['answer'],
});

export const QuestionnaireTypes = Types;
export default Creators;

/* ------------- Initial State ------------- */

export const INITIAL_STATE = Immutable({
answers: [],
});

/* ------------- Selectors ------------- */

export const QuestionnaireSelectors = {
getCurrentAnswers: (state: any) => state.answers,
};

/* ------------- Reducers ------------- */

const setAnswer = (state, { answer }) => {
  return ({
    ...state,
    answers: [...state.answers, answer],
  })
};

/* ------------- Hookup Reducers To Types ------------- */

export const reducer = createReducer(INITIAL_STATE, {
  [Types.SET_ANSWER]: setAnswer,
});

then in my component I simply do

const handleSubmitPress = (data) => {
  setAnswer({ question_id: currentQuestion.id, value: data.questionInput });
  console.log(getCurrentAnswers)
};

but every time this handler runs the log shows the previous state (an array containing all the already added but not the one added just in the previous line)

Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
  • Check this out: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately The set state is not synchronous. You will have the updated state on the next re-render. If you put the console.log outside of the handleSubmitPress, you will see that it is being called with the updated state on the next render – szczocik Oct 09 '20 at 10:20
  • thank, that solved the issue – Cereal Killer Oct 09 '20 at 16:37

0 Answers0