Skip to content

Commit

Permalink
useSite: simplify how Redux site is ensured to fetch just once (#94571)
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr authored Dec 9, 2024
1 parent 181792a commit 7c16b80
Showing 1 changed file with 9 additions and 16 deletions.
25 changes: 9 additions & 16 deletions client/landing/stepper/hooks/use-site.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { usePrevious } from '@wordpress/compose';
import { useSelect } from '@wordpress/data';
import { useEffect } from 'react';
import { useSelector, useDispatch } from 'calypso/state';
import { useDispatch } from 'calypso/state';
import { requestSite } from 'calypso/state/sites/actions';
import { getSite, isRequestingSite } from 'calypso/state/sites/selectors';
import { SITE_STORE } from '../stores';
Expand All @@ -14,11 +13,6 @@ export function useSite() {
const siteSlug = useSiteSlugParam();
const siteIdParam = useSiteIdParam();
const siteIdOrSlug = siteIdParam ?? siteSlug ?? '';
const selectedSite = useSelector( ( state ) => getSite( state, siteIdOrSlug ) );
const isRequestingSelectedSite = useSelector( ( state ) =>
isRequestingSite( state, siteIdOrSlug )
);
const lastRequestedSiteIdOrSlug = usePrevious( siteIdOrSlug );

const site = useSelect(
( select ) => {
Expand All @@ -31,15 +25,14 @@ export function useSite() {

// Request the site for the redux store
useEffect( () => {
if (
siteIdOrSlug &&
siteIdOrSlug !== lastRequestedSiteIdOrSlug &&
! selectedSite &&
! isRequestingSelectedSite
) {
dispatch( requestSite( siteIdOrSlug ) );
}
}, [ siteIdOrSlug, selectedSite, isRequestingSelectedSite ] );
dispatch( ( d, getState ) => {
const state = getState();
if ( getSite( state, siteIdOrSlug ) || isRequestingSite( state, siteIdOrSlug ) ) {
return;
}
d( requestSite( siteIdOrSlug ) );
} );
}, [ dispatch, siteIdOrSlug ] );

if ( siteIdOrSlug && site ) {
return site;
Expand Down

0 comments on commit 7c16b80

Please sign in to comment.