Home > Blockchain >  How to set useState while checking propsType
How to set useState while checking propsType

Time:05-13

hello I'm trying to set useState but it crashing the whole code. here I'm sending propstype from parent component to child component. so when propstype condition is checked/true then I'm trying to set useState but instead of setting it crashes. please checked below what I tried, Here I've removed unwanted code otherwise it'll too big for readers and they might lost the focus from question. can anyone suggest me any new solution for this I've tried a lot of and then came here for the proper solution.

parent component (BillComponent)

const BillComponent = () => {
return(  
{/* Add Bill form */}
        <Drawer
          title={"Add Bill"}
          placement="right"
          onClose={onClose}
          visible={visible}
          className="ant-drawer-half"
        >
          <AddBill parentCallback={handleCallback} type="add" />          // <---This AddBill is child component and here I'm passing props type as add
        </Drawer>
    </>
    </>
  );
};
export default BillComponent;

child component (AddBill)

const AddBill = (props) => {
const [checked, setChecked] = useState(false);

if(props.type === "add"){                       
    setChecked(false);          //<---This is where main code is crashing. when I set useState 
  }else{
    setChecked(true);
  }

return( 
// divs of project
 );
};
export default AddBill;

CodePudding user response:

Not sure if that's your case because you didn't show the error. Probably the error will be something related to "Too many re-renders".

It's a bad practice to use those React hooks in the "root" of the component. In your particular case, I'd do the following:

const [checked, setChecked] = useState(false);

useEffect(() => {
  if (props.type === "add") {
    setChecked(false);
  } else {
    setChecked(true);
  }
}, [props.type]);

CodePudding user response:

Please share the error you're getting. Also why not just use: const [checked, setChecked] = useState(props.type === 'add');

  • Related