Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react state is throwing `TypeError: setEnd is not a function` error?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
  })
}, [])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading