React setState error -> Objects are not valid as a React child Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React setState error -> Objects are not valid as a React child without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I continue to get the following error

Objects are not valid as a React child (found: object with keys {questionId, answer}). If you meant to render a collection of children, use an array instead.

I realise it is quite a common error on here but I can’t seem to figure it out. Any help or pointers in the right direction would be great.

const [currentQuestion, setCurrentQuestion] = useState(0)    
const [selectedAnswer, setAnswer] = useState('')
const [savedAnswers, setSavedAnswers] = useState([])

const question = questions[currentQuestion]

const handleNextQuestion = () => {
    if(currentQuestion < questions.length - 1) {

        //create answer array item
        const answer = {questionId: question, answer: selectedAnswer};

        //add saved answer to array
        setSavedAnswers(savedAnswers => [...savedAnswers, answer])

        //go to next question
        setCurrentQuestion(currentQuestion + 1)

        //clear next answer
        setAnswer('')
    }
}
return (
    <div className="section">
        <div className="container">
            <div className={styles.surveyContainer}>
                <h2 className="title is-2 has-text-centered">Feel</h2>

                <Progress 
                    total = {questions.length}
                    current = {currentQuestion + 1}
                />
                <Question 
                    question = {question.question}
                />
                <Answers
                    answers = {question}
                    selected = {selectedAnswer}
                    handleClick = {handleClick}
                />
            </div>
            <button className="button is-primary" onClick={handleNextQuestion}>Next</button>

            {selectedAnswer}Selected Answers
            {savedAnswers}Saved Answers
        </div>
    </div>
)

enter image description here

Answer

You need to map the array of answers. Use the questionId for the react key.

savedAnswers.map(({ questionId, answer }) => (
  <div key={questionId}>{answer}</div>
));
We are here to answer your question about React setState error -> Objects are not valid as a React child - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji