'React: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setState')
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! :-)
Solution 1:[1]
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...')
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | smith chokshi |
| Solution 2 | adel |
