I'm indexing transactions as they are confirmed. I poll the web3.eth.getBlock with the next number and I put them in a database. But, I've realized that some transactions have an incorrect block number. I suppose that the problem is that I've got the incorrect block branch and finally another branch was the one kept in the blockchain. How I can prevent this situation? web3.eth.getTransactionReceipt can prevent this situation?
A. You can wait for further block confirmations before writing to your database. It's like being X minutes behind, so that you don't have to deal with a chain reorg. See What number of confirmations is considered secure in Ethereum? and note one of the answers is to combine waiting and use multiple clients.
B. If you want to deal with chain reorgs, you can indeed make use of
web3.eth.getTransactionReceipt and for example code see:
How can a DApp detect a fork or chain reorganization using web3.js or additional libraries?