Reputation: 38
As you can see below, I'm calling the isChecked prop from the <Todo/>
parent component. I need to change it's value depending on the user's click, so I'm using 'useState' and setting up an event. The problem is that I can't send it to the API named as currentCheck, it needs to be named isChecked again so my API can recognize and save the new value.
Obs: I'm new to React and I'm just training, so this may be a silly question, sry.
function Todo({ _id, text, isChecked }) {
const [currentCheck, setCurrentCheck] = useState(isChecked),
[icon, setIcon] = useState(ellipseOutline)
async function handleClick() {
if (currentCheck) {
setCurrentCheck(false)
setIcon(ellipseOutline)
return await api.put('/', { _id, currentCheck })
}
setCurrentCheck(true)
setIcon(checkmarkCircle)
return await api.put('/', { _id, currentCheck })
}
Upvotes: 0
Views: 53
Reputation: 735
I think that you should write your code as below :
function Todo({ _id, text, isChecked }) {
const [currentCheck, setCurrentCheck] = useState(isChecked),
[icon, setIcon] = useState(ellipseOutline)
async function handleClick() {
if (currentCheck) {
setCurrentCheck(preve => !preve)
setIcon(ellipseOutline)
return await api.put('/', { _id, isChecked: currentCheck })
}
setCurrentCheck(preve => !preve)
setIcon(checkmarkCircle)
return await api.put('/', { _id, isChecked: currentCheck })
}
Please test it and write your feedback in comment
Upvotes: 0
Reputation: 1332
As far as I understood your question. Your API request looks like {_id: 1, isChecked: true}
and you need isChecked
attribute instead of currentCheck
.
You can do it in this way
function Todo({ _id, text, isChecked }) {
const [currentCheck, setCurrentCheck] = useState(isChecked),
[icon, setIcon] = useState(ellipseOutline)
async function handleClick() {
if (currentCheck) {
setCurrentCheck(false)
setIcon(ellipseOutline)
return await api.put('/', { _id, isChecked : currentCheck })
}
setCurrentCheck(true)
setIcon(checkmarkCircle)
return await api.put('/', { _id, isChecked : currentCheck })
}
This can also be written as
function Todo({ _id, text, isChecked }) {
const [currentCheck, setCurrentCheck] = useState(isChecked),
[icon, setIcon] = useState(ellipseOutline)
async function handleClick() {
setCurrentCheck((prevState) => !prevState);
setIcon(() => currentCheck ? ellipseOutline : checkmarkCircle);
return await api.put('/', { _id, isChecked : currentCheck })
}
Upvotes: 1