Reputation: 332
From "orders" component, sending a order id to "update" component. Then trying to update "the status" of the order containing the id.
Logging the id value in the console works, but not setting a state with it.
"Update" component:
const UpdateStatus = (props) => {
const location = useLocation();
const [orderId, setOrderId] = useState(null);
const [status, setStatus] = useState("pending");
useEffect(() => {
setOrderId(location.state.id); // errors here
console.log(location.state.id) // but gives a valid id
}, [location]);
const handleChange = e => {
setStatus(e.target.value);
console.log(e.target.value)
}
const history = useHistory();
const handleClick = () => {
if (orderId){
axios.patch(`http://localhost:5000/orders/change-status/${orderId}`, {status: status}, {withCredentials: true})
.then((res) => {
console.log(res);
history.push("/get-orders");
})
}
}
return (
<div>
<h2> Update Order Status </h2>
<form>
<label>Change status to: </label>
<select name="status" id="order-status" onChange={handleChange}>
<option value="pending">Pending</option>
<option value="accepted">Accepted</option>
<option value="delivered">Delivered</option>
</select>
<br/><br/>
<input type="submit" value="Submit" onClick={handleClick}/>
</form>
</div>
);
}
"Orders" component:
const handleClick = orderId => {
history.push({
pathname: '/update-status',
state: { id: orderId }
});
}
Upvotes: 1
Views: 5972
Reputation: 98
Try something like:
useEffect(() => {
if(location?.state?.id)
setOrderId(location.state.id);
}, [location?.state?.id]);
Upvotes: 2
Reputation: 9321
Try this:
useEffect(() => {
setOrderId(location.state?.id);
..........
}, [location]);
Upvotes: 0