I have an app that shows some questions when the user presses a button. On each questions I have a condition to determine if the "Back" button should be shown on the question - appState.questions.length > 0
.
My problem is that the state is not being reached from the function where I am calling it.
let questionComponent = (currentCardKey, textAreaText = "") => {
console.log(`Question length inside: ${appState.questions.length}`)
return <Question
textAreaText={"ereer"}
// I can not access appState from here.
shouldShowBackButton={appState.questions.length > 0}
measureTextChangeHandler={measureTextChangeHandler}
onChosenDataTypeChanged={onChosenDataTypeChanged}
aimTextChangeHandler={aimTextChangeHandler}
onButtonClicked={onButtonClicked}
currentCardKey={currentCardKey}/>
}
The structure of my code.
function App(){
const [appState, setAppState] = useState(
{
questions: [], //[<Question />, <Question />]
independentVariablesCount: 0,
}
)
const [currentCard, setCurrentCard] = useState();
const addToQuestion = (questionObject) => {
setAppState(prevState => {
questionLength.current = appState.questions.length
return {...prevState, questions: [...prevState.questions, questionObject]}
})
}
// I can access appState outside the function
let questionComponent = (currentCardKey, textAreaText = "") => {
console.log(`Question length inside: ${appState.questions.length}`)
return <Question
textAreaText={"ereer"}
// I can not access appState inside this function
shouldShowBackButton={appState.questions.length > 0}
measureTextChangeHandler={measureTextChangeHandler}
onChosenDataTypeChanged={onChosenDataTypeChanged}
aimTextChangeHandler={aimTextChangeHandler}
onButtonClicked={onButtonClicked}
currentCardKey={currentCardKey}/>
}
const onButtonClicked = (_buttonText, previousCardComponent) => {
const previousCard = previousCardComponent
const previousCardMainText = previousCardComponent.props.mainText
...
switch (_buttonText) {
case buttonText["NEXT"]:
switch (previousCardMainText){
case questionData["CAT_QUESTION"]:
addToQuestion(previousCard)
setCurrentCard(questionComponent("CAT_FOOD_QUESTION"))
break
}
...
break
}
}
return (
<div>{currentCard}</div>
)
}
I have tried updating the function inside useEffect()
but that does not solve the problem. I have searched for solutions such as useState function is not working in functional component and React hooks setState not updating immediately but none of these work.
How can this issue be resolved?