Although the state is updated the input tag’s value still shows the last state of the object.
Here is my code:
const OrderForm = ({selectedOrder, setSelectedOrder }) => {
const [order, setOrder] = useState({});
useEffect(() => {
setOrder(selectedOrder);
}, [selectedOrder]);
return (
<section className={styles.formSection}>
{order.id !== undefined && (
<div className={styles.formRow}>
<button
className={styles.clear}
onClick={() => {
setSelectedOrder({});
setOrder({});
}}
>
Clear
</button>
</div>
)}
<div className={styles.formRow}>
<div className={styles.formGroup}>
<span className={styles.formLabel}>
Customer name {order.customer_name}
</span>
<input
type='text'
className={styles.formInput}
placeholder='Enter Customer name'
value={order.customer_name}
onChange={(e) =>
setOrder({ ...order, customer_name: e.target.value })
}
/>
</div>
</div>
</section>
)
Here the input values gets updated whenever the selectedOrder
gets updated from a sibling component but on clicking the Clear
button, although order
object updates the input values still shows the last state content.