I am trying to read a react state when the callback of chrome.tabs.onUpdated.addListener is being called, but it seems the state value is undefined, even though it's set previously.
Here is the hook that I have made.
export const useCurrentTab = () => {
const [currentTab, setCurrentTab] = useState<chrome.tabs.Tab | undefined>(undefined)
const [activeTabId, setActiveTabId] = useState<number | undefined>(undefined)
const getActiveTab = async () => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
console.log(`Setting current tab id to ${tab?.id}`)
setActiveTabId((prevActiveTabId) => tab?.id || prevActiveTabId)
return tab
}
const updateCurrentTab = (
tabId: number,
changeInfo: chrome.tabs.TabChangeInfo,
tab: chrome.tabs.Tab
) => {
console.log("updateCurrentTab", activeTabId, currentTab, tabId);
if (changeInfo.status === 'complete' && tabId === activeTabId) {
console.log(`Tab ${tabId} status changed to ${changeInfo.status}`)
setCurrentTab(tab)
}
}
useEffect(() => {
getActiveTab().then((tab) => {
if (tab && tab.status === 'complete') {
setCurrentTab(tab)
}
})
chrome.tabs.onUpdated.addListener(updateCurrentTab)
return () => {
chrome.tabs.onUpdated.removeListener(updateCurrentTab)
}
}, [])
return currentTab
}
the issue is currentTab isn't updated after the page is loaded, I have debugged and pin pointed the issue by adding console logs.
console.log("updateCurrentTab", activeTabId, currentTab, tabId);
when logging, it shows the activeTabId is undefined, so the check for tabId === activeTabId fails here.
here is the console log in order.
current-tab.tsx:15 Setting current tab id to 1494595641
current-tab.tsx:25 updateCurrentTab undefined undefined 1494595641