I am working on essentially a survey website. One of the components is called a BiSlider which is just a switch. These switches have a default value which I have defined in a list of questions (ie "yes" is defualt out of a yes/no switch), to achieve this I call the parent function onChange at the component mount with useEffect(). However this just sends an empty object to the parent {}. However, when you toggle the switch it works perfectly - sending an object containing { questionTitle: { answer: "yes", valid: true } }. Could I have a hand working out why it cannot send an answer object.
Here is the biSlider component:
export const BiSlider = ({ choices, question, onChange, auto }) => {
const [ selected, setSelected, selectedRef ] = useState(auto)
useEffect(() => {
onChange({ [question]: { answer: choices[selectedRef.current], valid: true } })
}, [])
const onSwitch = () => {
setSelected(i => ( i === 0 ) ? 1 : 0)
onChange( { [question]: { answer: choices[selectedRef.current], valid: true } } )
}
return (
<div className={"bislider" + (selected ? " on" : " off")}>
<div className="slider"></div>
<button onClick={() => onSwitch()} className="bislider-button">{ choices[1] }</button>
<button onClick={() => onSwitch()} className="bislider-button">{ choices[0] }</button>
</div>
)
}
The question prop would just be the question title in a string, the choices props would be a list of options (ie ["yes", "no"]) and the auto prop is the index of the default value (ie 0 for no).
Hope I explained this ok, if you need more code please just give me a shout.