FlashspeedIfe
FlashspeedIfe

Reputation: 378

React hooks set state being called multiples times when updating state

I have an app like this

function App(){
    const [appState, setAppState] = useState(
        {
            questions: []
        }
    )

    const addToQuestion = (questionObject) =>{

        setAppState((prevState) => {
            return {...prevState, questions: [...prevState.questions, questionObject]}
        })

    }

    let removeFromQuestionArray = () => {
        setAppState((prevState) => {
            let a = prevState.questions
            a.pop()
            return {...prevState, questions: a}
        })
    }

    const onBackButtonClicked = () => {
        removeFromQuestionArray()
    }
}

But when I call removeFromQuestionsArray() the setAppState works unpredictably. It sometimes removes all the items in the array even though I'm only popping the last item in the array. What could be causing this. I just want to remove the last item from the array, how can I go about this without having issues?

Upvotes: 0

Views: 49

Answers (1)

Brother58697
Brother58697

Reputation: 3178

Your code works fine.

Posting this as an answer to show the snippet:

Note: I edited the addToQuestions function to make it work for the example, but I didn't touch removeFromQuestionsArray

const { useState, useRef } = React

function App(){
    const [appState, setAppState] = useState(
        {
            questions: [
              'What is Love',
              'Whats the meaning of life',
              'Whats the answer to this question'
            ]
        }
    )
    
    const input = useRef();

    const addToQuestion = () =>{
        let question = input.current.value;
        setAppState((prevState) => {
            return {...prevState, questions: [...prevState.questions, question]}
        })
        input.current.value = '';
        input.current.focus();

    }

    let removeFromQuestionArray = () => {
        setAppState((prevState) => {
            let a = prevState.questions
            a.pop()
            return {...prevState, questions: a}
        })
    }
  return (
  <div>
    {appState.questions.map(question => <li>{question}</li>)}
    <input ref={input}></input>
    <button onClick={addToQuestion}>Add Question</button>
    <button onClick={removeFromQuestionArray}>Remove</button>
  </div>
  )
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
,
  root
)
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions