Reputation: 59
I am trying to implement tick on value set to true and no tick on value set to false from redux state but checkbox is always set to tick on server start. My onchange handler is also working fine and console.log is also displaying correct values.
My code is as follow-
const TaskItem = ({tasks:{task,_id,date,checkbox},deleteTodo,loading}) => {
const [formData,setformData]=useState({
checkbox1:{checkbox}
})
const {checkbox1}=formData;
console.log(checkbox1);
const onChange=e=>{
setformData({...formData,[e.target.name]:e.target.checked})
}
return (
<div className="list">
<p>
<Moment style={{backgroundColor:"rgba(27,112,137)", border:"1px"}}
format='YYYY/MM/DD hh:mm a'>
{date}
</Moment>
<br/>
<input
name="checkbox1"
type="checkbox"
checked={checkbox1}
onChange={e=>onChange(e)}
/>
{task}
<span>
<i className="fas fa-trash" onClick={()=>{deleteTodo(_id)}}></i>
</span>
</p>
</div>
)
}
TaskItem.propTypes = {
tasks:PropTypes.object.isRequired,
deleteTodo:PropTypes.func.isRequired,
}
export default connect(null,{deleteTodo}) (TaskItem)
Upvotes: 0
Views: 81
Reputation: 8273
const [formData,setformData]=useState({
checkbox1:{checkbox}
})
is equivalent to:
const [formData,setformData]=useState({
checkbox1:{checkbox: checkbox}
})
so <input checked={checkbox1} />
is like : <input checked={{checkbox: false}} />
at start, so the checkbox will be checked. (since {checkbox: false}
is truthy
.)
so based on the type of checkbox
redux state, change it. if it's a true/false value, change your code to :
const [formData,setformData]=useState({
checkbox1: checkbox
})
if it's a object and has a checked property, change it to: checkbox1: checkbox.ischecked
Upvotes: 2