skip to Main Content

I am trying to output different components based on the inputType, however the component or anything that goes into the DOM does not render (aka console.logs fire correctly to confirm the if/if else statements are working correctly. Not quite sure how to resolve as we cannot move it into a class based component because you cannot use react hooks inside a class based component and we currently use the useStaticQuery react hook to query WordPress.

    const ServiceQuestions = filter => {
    const { allWpService } = useServiceQuery()

    const renderQuestions = id => {
        allWpService.nodes.map(service => {
        if (service.id === id.filter) {
            service.serviceQuestions.questions.map(question => {
            question.questionInputField.map(inputField => {
                if (inputField.inputType === "text") {
                console.log(inputField.inputType)
                } else if (inputField.inputType === "number") {
                console.log(inputField.inputType)
                } else if (inputField.inputType === "radio") {
                return <InputCheckboxImageTop />
                } else {
                console.log("Cannot determine the inputType")
                }
            })
            })
        }
        })
    }

    return <>{renderQuestions(filter)}</>
    }

2

Answers


  1. Chosen as BEST ANSWER

    As per a comment suggested above, I removed the nested maps and instead used forEach loops which worked a charm, so for future reference here's the solution:

    const ServiceQuestions = filter => {
        const { allWpService } = useServiceQuery()
    
        const renderQuestions = id => {
        allWpService.nodes.map(service => {
            if (service.id === id.filter) {
            service.serviceQuestions.questions.forEach(data => {
                data.questionInputField.forEach(field_data => {
                if (field_data.inputType === "text") {
                    console.log(field_data.inputType)
                } else if (field_data.inputType === "number") {
                    console.log(field_data.inputType)
                } else if (field_data.inputType === "radio") {
                    return <InputCheckboxImageTop />
                } else {
                    console.log("Cannot determine the inputType")
                }
                })
            })
            }
        })
        }
    
        return <>{renderQuestions(filter)}</>
    }
    

  2. Your renderQuestions function doesn’t return the result array

    You can replace

    const renderQuestions = id => {
            allWpService.nodes.map(service => {
    

    by

    const renderQuestions = id => {
            return allWpService.nodes.map(service => {
    

    or use parentheses instead of curly brackets around your allWpService.nodes.map

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search