I am getting this error:
Actually, I am trying to change the button text for a few seconds when I click on the button.
This is basically for Add To Cart Button, I want to hold the button process for a few seconds for my API call in the same function.
My Code:
const AddToCart = async (sku) => {
this.setState({ buttonText: "Loading..." });
setTimeout(() => {
this.setState({ buttonText: "Saved" });
}, 5000);
}
const [value, setvalue] = useState([]);
const initialState = "ADD TO CART";
const [buttonText, setButtonText] = useState("ADD TO CART");
render() {
return (
<a onClick={()=>{AddToCart(item.sku)}} className="add-to-cart-btn">
<i className="fa fa-solid fa-cart-shopping"></i>{buttonText}</a>
);
}
My Final code is what I am trying to do.
const AddToCart = async (sku) => {
this.setState({ buttonText: "Loading..." });
const user_id = localStorage.getItem('card_id');
let product_details = {
sku_name: sku,
qty: 1,
quote_id: user_id
}
setTimeout(() => {
this.setState({ buttonText: "Saved" });
}, 5000);
dispatch(useraction.addtocartRequest(product_details));
}
I am new to this technology. Any other suggestions also help me a lot. Thank you very much for your consideration! :-)
CodePudding user response:
Here you are using this.setState
which is used for class-based components but you are using functional-based component so instead of this.setState
simply write setButtonText('Loading...')
https://reactjs.org/docs/hooks-intro.html
CodePudding user response:
you should use react hooks instead of this.setState
, here how to do it:
const [buttonText, setButtonText] = useState("ADD TO CART");
// buttonText is value getter
// setButtonText is value setter
so if you want to update the value of you state:
setButtonText(newValue)