Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

React hook useState doesn't update array from the first time [duplicate]

$
0
0

I have a problem with useState hook. I'm trying to do some kind of tests. But I don't understand how it works. I have two components - SurveyScreen and QuestionItem:

const SurveyScreen: React.FC = () => {    const [answersList, setAnswersList] = useState<Answer[]>([]);    // ...    return (       {/* ... */}<QuestionItem           completeSurvey={completeSurvey}           answersList={answersList}           setAnswersList={setAnswersList}           step={step}           setStep={setStep}           index={index}           question={question}           questionsCount={survey.questions.length}           key={question.id.toString()}       />    );}
const QuestionItem: React.FC<IQuestionItemProps> = ({  step,  setStep,  index,  question,  questionsCount,  answersList,  setAnswersList,  completeSurvey,}) => {  const [singleAnswerId, setSingleAnswerId] = useState<number | null>(null);  const [answersIds, setAnswersIds] = useState<number[]>([]);  const addAnswer = (): void => {    let answer: Answer;    if (question.multiple && answersIds.length) {      answer = {        id: question.id,        user_comment: '',        checked: answersIds,      };      console.log(answer);    } else if (singleAnswerId) {      answer = {        id: question.id,        user_comment: '',        checked: singleAnswerId,      };      console.log(answer);    }    setAnswersList(answersList => [...answersList, answer]);    console.log(answersList); // <- [] from the first time  };  return (<TouchableOpacity        onPress={addAnswer}        style={{...mainStyles.alignCenterRow, marginTop: 90}}><Text style={styles.continueText}>Continue</Text><EvilIcons name="arrow-right" size={30} color="#007fff" /></TouchableOpacity>  );}

When I try to add the answer to list, it doesn't update the array from the first time. It outputs empty array.

What am I doing wrong and how can I fix it?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>