🐛 Validate the initial tab, improve component

This commit is contained in:
Philipp Stracker 2024-10-28 16:58:50 +01:00
parent 48d87100de
commit b369756cfd
No known key found for this signature in database

View file

@ -1,15 +1,34 @@
import { memo, useCallback, useEffect, useState } from '@wordpress/element';
import { TabPanel } from '@wordpress/components';
import { getQuery, updateQueryString } from '@woocommerce/navigation';
import { useEffect, useState } from '@wordpress/element';
const TabNavigation = ( { tabs } ) => {
const initialPanel = getQuery()?.panel ?? tabs[ 0 ].name;
const [ activePanel, setActivePanel ] = useState( initialPanel );
const { panel } = getQuery();
const updatePanelUri = ( tabName ) => {
setActivePanel( tabName );
const isValidTab = ( tabsList, checkTab ) => {
return tabsList.some( ( tab ) => tab.name === checkTab );
};
const getValidInitialPanel = () => {
if ( ! panel || ! isValidTab( tabs, panel ) ) {
return tabs[ 0 ].name;
}
return panel;
};
const [ activePanel, setActivePanel ] = useState( getValidInitialPanel );
const updatePanelUri = useCallback(
( tabName ) => {
if ( isValidTab( tabs, tabName ) ) {
setActivePanel( tabName );
} else {
console.warn( `Invalid tab name: ${ tabName }` );
}
},
[ tabs ]
);
useEffect( () => {
updateQueryString( { panel: activePanel }, '/', getQuery() );
}, [ activePanel ] );