React hook form checkbox always true

Asked

Viewed 291 times

0

I have a question when receiving the database data for my checkboxes. Even the value coming false from the bank, the checkbox is checked.

I’ve tried several forum responses but I must be missing something.

I get json from the bank and looping using map with each key correspondent.

In the case below, host.hostwould be equivalent to the returned json of res.data.host:

data: {
    host: "false"
}

Home js.

function Home() {

const { handleSubmit, register, errors } = useForm()

const [users, setUsers] = useState([])

const [file, setFile] = useState('')

useEffect(() => {
    async function loadUser() {

        const userId = localStorage.getItem('id')
        const res = await axios.post(`${process.env.REACT_APP_GET_USER_DATA_URL}/react-getUserData.php`, { userId })
        console.log(res)

        setUsers([...users, res.data])
    }
    loadUser()

    register({ name: 'file' })
}, [register])

function handleChange(e) {
    const isChecked = e.target.checked
    console.log(isChecked)
}

...

return (
    <>

<label className="btn btn-circle border filters-btn">
{users.map((host) => (
     <input
        type="checkbox"
        name="host"
        id="host"
        key={host}
        defaultChecked={host.host}
        ref={register}
        onChange={handleChange}
     />
))}
<i></i>
<span>Hospedagem</span>
</label>
  • host is in text so it’s true, it needs to be host: false to make the expected effect, that is, the kind that is hindering its development.

1 answer

2


The variable that is returning from your bank is not in the format of true or phony (boolean), is a text, thus being true for the ,

Example:

function App() {
  const [value, setValue] = React.useState(false);
  const [texto, setTexto] = React.useState('false');
  return (
    <div>
      <div style={{height: '50px'}}>
        <p>{value.toString()}</p>
        <button onClick={e => setValue(!value)}>
            Mudar estado no formato verdadeiro ou falso
        </button>
      </div>
      <div style={{height: '50px'}}>
        <p>{texto?"verdade":"falso"}</p>
        <button onClick={e => setTexto('false'?'true':'false')}>
          Mudar estado do texto
        </button>
      </div>
    </div>
  )
 }
 ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

to solve your problem quickly and if you can send the information in the true or false format of your bank, or else, solve with a simple comparison with the text sent, example:

defaultChecked={host.host === 'true'}
  • 1

    show guy...thank you so much! I’m still new in React so sorry if I missed anything. hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.