React Node Telegram bot problem with mainButtonClicked

14 views Asked by At

I had a problem with sending data to the server and then having this data sent to me in the telegram bot.

When the 'Buy' button (mainButtonClicked) is pressed, nothing happens, nothing is sent to the server either, but if you configure the button to send data to the server when you press 'Add', then everything is sent.

Here is the code on github, the main reasons are in the sections: tg-web-app-node/index.js and in tg-web-appreact/src/components/ProductList/ProductList.jsx

Link: https://github.com/Topicesst/tg-web-app-node.git https://github.com/Topicesst/tg-web-app-react.git

Here is the problematic code:

const getTotalPrice = (items = []) => {
     return items.reduce((acc, item) => {
         return acc += item.price
     }, 0)
}

const ProductList = () => {
     const [addedItems, setAddedItems] = useState([]);
     const {tg, queryId} = useTelegram();

     const onSendData = useCallback(() => {
         const data = {
             products: addedItems,
             totalPrice: getTotalPrice(addedItems),
             queryId,
         }
         fetch('http://80.85.143.220:8000/web-data', {
             method: 'POST',
             headers: {
                 'Content-Type': 'application/json',
             },
             body: JSON.stringify(data)
         })
     }, [addedItems])

    useEffect(() => {
         tg.onEvent('mainButtonClicked', onSendData)
         return () => {
             tg.offEvent('mainButtonClicked', onSendData)
         }
     }, [onSendData])


     const onAdd = (product) => {
         const alreadyAdded = addedItems.find(item => item.id === product.id);
         let newItems = [];

         if(alreadyAdded) {
             newItems = addedItems.filter(item => item.id !== product.id);
         } else {
             newItems = [...addedItems, product];
         }

         setAddedItems(newItems)

         if(newItems.length === 0) {
             tg.MainButton.hide();
         } else {
             tg.MainButton.show();
             tg.MainButton.setParams({
                 text: `Buy ${getTotalPrice(newItems)}`
             })
         }
     }

     return (
         <div className={'list'}>
             {products.map(item => (
                 <ProductItem
                     product={item}
                     onAdd={onAdd}
                     className={'item'}
                 />
             ))}
         </div>
     );
};

export default ProductList;

Bduu is very grateful for the help, because even acquaintances could not help solve the problem (

I checked whether the button responds and whether it sends at least some data to the server - it does.

0

There are 0 answers