Home > Software engineering >  Initial state value not being read (React)
Initial state value not being read (React)

Time:11-20

I'm building an application that revolves around recording payments. I have a state that's along the lines of

 const [state, setstate] = useState({
    amountPaid: Number(bill.total), // bill comes from another component fully populated
    datePaid: new Date(),
  });

I'm trying to render it in a MUI component (A modal)

return (
    <div>
      <form>
             <TextField
              type="number"
              label="Enter the amount you are paying"
              onChange={(e) =>
                setState({ ...state, amountPaid: e.target.value })
              }
              value={state.amountPaid}
            />

When I submit the form, I update the bill as such, with the amount I paid (might be less than the whole amount needed)

useEffect(() => {
      setPayment({
        ...payment,
        amountPaid: Number(bill.total) - Number(bill.totalAmountReceived),
      });
  }, [bill]);

When I reopen the modal to check for the updated amount, the amountPaid row is correctly displayed according to the above logic. But the amountPaid is displayed as null initially, whereas the date is displayed correctly. Why doesn't it initialize to bill.total?

Would be glad to provide any addition details that are needed.

CodePudding user response:

You can only set component level initialization in any react component. If you want to set some value from previous/any parent component you will need to update the initial state value with the following expression:

If you are using a class based component the use componentDidMount(), if function based then use useEffect()

const[state,setState]=useState({ 
    amountPaid: 0,
    datePaid: new Date()
};

useEffect(()=>{
    setState({...state,state.amountPaid:Number(bill.total) , 
   //assuming bill is coming as a prop from another component
},[]);

One more suggestion is try not to use the state altering functions inside render, use a separate function and call state update logic in it

  • Related