I’m passing a state hook to my component and changing the value with conditional statement. why is this happening?
in my root component
const [done, setDone] = useState(0);
<FirstStep current={current} end={done} setEnd={setDone} />;
and in the component i’m using it inside useEffect
useEffect(() => {
if (
plateInput != null &&
mileageInput != null &&
makeInput != null &&
bodyInput != null &&
yearInput != null &&
kindInput != null &&
transmissionInput !== null
) {
console.log("object cleared");
setEnd(current);
// dispatch(setCompletedStep(current));
} else {
console.log("object is not cleared");
setEnd(current - 1);
// dispatch(setCompletedStep(current - 1));
}
}, [
plateInput,
mileageInput,
makeInput,
bodyInput,
yearInput,
kindInput,
transmissionInput,
]);
the error is TypeError: setEnd is not a function. why is this happening?
>Solution :
it looks like an error when receiving the props in FirstStep component,
you need to make sure of some points
- in your root component make sure to import useState from react
import {useState} from 'react';
- make sure to pass the props correctly to your nested components
const MyRoot = () => {
const [done, setDone] = useState(0);
return <FirstStep current={current} end={done} setEnd={setDone} />;
}
- make sure to recive th props correctly in your FirstStep component
// you can destructuring to get the props
const FirstStep = ({end, setEnd, current}) => {
if(data != null){
setEnd(current);
} else {
setEnd(current - 1);
}
return <p>test</p>
}
UPDATE:
try to set the state inside useEffect and use the callback function to check the current instead
import {useEffect} from 'react';
useEffect(() => {
setEnd(() => {
if(data !== null) {
return current
}else {
return current - 1
}
})
}, [])