Search code examples
reactjsstatereact-hooksreact-contextuse-reducer

React Hooks - Context Provider is not immediately reflecting dispatched state


My Goal: I'm creating a table that displays data to users. Based on a certain value stored in global state (stored in a reducer function that the context API provides to other components), I am fixing that header to the top of the page on scroll, but only when the table is in view. To do this, I have to register an on Scroll and on Resize event listener to recalculate the tables position when the user scrolls or resizes the screen. I want to update the global state to be isHeaderActivelyFixed: true only when the table is in view and the state is not already set to isHeaderActivelyFixed: true. Otherwise, i would be constantly updating state every time the table is in view and the user scrolls to isHeaderActivelyFixed: true and likewise when its not in view to isHeaderActivelyFixed: false

The Problem: I have the above scenario set up the way I believe I need to. However, when i dispatch to global state and then console log or use that global state, it doesn't reflect what i just dispatched to it. The react dev tools DO show the updated state I dispatched but I need to be able to update that newly dispatched state in the function i dispatched it in. This way I know not to dispatch it again. I hope that makes sense. Thanks in advance!

Code: (Note: I stripped out unnecessary code, so some things may seem set up odd. I left some code in to provide context to the problem. The areas where i commented are where the issues are arising. The isActivelyViewed() function just gets the tables getBoundingClientRect() and checks if its in view still )

ProductTableStore.jsx

import React from 'react';

const initialState = {
  isLoading: true,
  isSelectable: null,
  isHeaderFixedOnScroll: null,
  isHeaderActivelyFixed: null,
  isAddToCartEnabled: null,
  productTableActiveWidth: null,
  addToCartData: null,
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'setIsHeaderFixedOnScroll':
      return {
        ...state,
        isHeaderFixedOnScroll: action.isHeaderFixedOnScroll,
      };
    case 'setIsHeaderActivelyFixed':
      return {
        ...state,
        isHeaderActivelyFixed: action.isHeaderActivelyFixed,
      };
    case 'setProductTableActiveWidth':
      return {
        ...state,
        productTableActiveWidth: action.productTableActiveWidth,
      };
    default:
      throw new Error(
        `Unexpected or missing action type. Action type provided was: ${action.type}`
      );
  }
};

const ProductTableContext = React.createContext({});

const ProductTableStore = () => {
  return React.useContext(ProductTableContext);
};

const ProductTableProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  return (
    <ProductTableContext.Provider value={[state, dispatch]}>
      {children}
    </ProductTableContext.Provider>
  );
};

export { ProductTableStore, ProductTableProvider };

ProductTable.jsx (The file I have the problem in)

import React from 'react';
import { ProductTableStore } from './ProductTableStore/ProductTableStore';
import { isActivelyViewed } from '../../js/helpers';

const ProductTable = ({ heading, ariaLabel, children }) => {
  const [globalState, dispatch] = ProductTableStore();

  const [isOnScrollResizeEventRegistered, setIsOnScrollResizeEventRegistered] = React.useState(
    null
  );

  const ProductTableRef = React.useRef(null);

  const registerOnScrollResizeEvent = (ref, resolve) => {
    console.log('Registering onScrollandResize');
    window.addEventListener(
      'scroll',
      _.throttle(() => {
        calculatePosition(ref);
      }),
      10
    );
    window.addEventListener(
      'resize',
      _.throttle(() => {
        calculateProductTableValues(ref);
      }),
      10
    );
    if (resolve) resolve();
  };

  const setIsHeaderActivelyFixed = (isHeaderActivelyFixed) => {
    console.log('fx setIsHeaderActivelyFixed. Passed argument:', isHeaderActivelyFixed);
    dispatch({
      type: 'setIsHeaderActivelyFixed',
      isHeaderActivelyFixed,
    });
    console.log('isHeaderActivelyFixed', globalState.isHeaderActivelyFixed); 
    // This comes back null and idk why! I thought it may be because there hasn't been a re-render but 
    // changing the callback on the effect below doesn't seem to change that

  };

  const setProductTableActiveWidth = (productTableActiveWidth) => {
    console.log('fx setProductTableActiveWidth');
    dispatch({
      type: 'setProductTableActiveWidth',
      productTableActiveWidth: `${productTableActiveWidth}px`,
    });
    console.log('productTableActiveWidth', globalState.productTableActiveWidth);
    // This comes back null and idk why! I thought it may be because there hasn't been a re-render but 
    // changing the callback on the effect below doesn't seem to change that
  };

  const calculatePosition = (ref) => {
    if (isActivelyViewed(ref.current) && !globalState.isHeaderActivelyFixed) {
      setIsHeaderActivelyFixed(true);
    } else if (!isActivelyViewed(ref.current) && globalState.isHeaderActivelyFixed) {
      // This never works because globalState never reflects updates in this function
      setIsHeaderActivelyFixed(false);
    } else {
      console.log('None of these...');
    }
  };

  const calculateWidth = (ref) => {
    if (ref.current.offsetWidth !== globalState.productTableActiveWidth) {
      setProductTableActiveWidth(ref.current.offsetWidth);
    }
  };

  const calculateProductTableValues = (ProductTableRef, resolve) => {
    calculateWidth(ProductTableRef);
    calculatePosition(ProductTableRef);
    if (resolve) resolve();
  };

  React.useEffect(() => {
    if (!globalState.isHeaderFixedOnScroll) return;
    new Promise((resolve, reject) => {
      if (isOnScrollResizeEventRegistered) reject();
      if (!isOnScrollResizeEventRegistered) {
        // Calculate intital PT width so that we only have to recalculate on resize
        calculateProductTableValues(ProductTableRef, resolve);
      }
    })
      .then(() => {
        registerOnScrollResizeEvent(ProductTableRef);
      })
      .then(() => {
        setIsOnScrollResizeEventRegistered(true);
      })
      .catch((err) => {
        console.error(
          'Unable to create promise for fixing the Product Table Header on scroll. The error returned was: ',
          err
        );
      });
  }, [globalState.isHeaderFixedOnScroll]);

  return (
    <ThemeProvider theme={getSiteTheme(_app.i18n.getString({ code: 'styledComponents.theme' }))}>
      <StyledProductTableContainer>
        {globalState.isAddToCartEnabled && (
          <StyledAddToCartContainer>
            <AddToCartForm
              buttonText={_app.i18n.getString({ code: 'cart.add.allItems' })}
              isDisabled={globalState.addToCartData.length === 0}
              ajaxData={globalState.addToCartData}
            />
          </StyledAddToCartContainer>
        )}
        {heading && <FeaturedHeader>{heading}</FeaturedHeader>}
        <StyledProductTable ref={ProductTableRef} ariaLabel={ariaLabel}>
          {globalState.isLoading && (
            <ThemeProvider theme={loadingStyles}>
              <StyledLoadingSpinner />
            </ThemeProvider>
          )}
          {children}
        </StyledProductTable>
      </StyledProductTableContainer>
    </ThemeProvider>
  );
};

const ProductTableHeader = ({ children }) => {
  const [globalState] = ProductTableStore();
  return (
    <StyledProductTableHeader
      isSelectable={globalState.isSelectable}
      isHeaderFixedOnScroll={globalState.isHeaderFixedOnScroll}
      isHeaderActivelyFixed={globalState.isHeaderActivelyFixed}
      fixedWidth={globalState.productTableActiveWidth}
    >
      {globalState.isSelectable && (
        <StyledProductTableLabel isSelect>Select</StyledProductTableLabel>
      )}
      {children}
    </StyledProductTableHeader>
  );
};

const ProductTableRow = ({ children }) => {
  const [globalState] = ProductTableStore();

  return (
    <StyledProductTableRow isSelectable={globalState.isSelectable}>
      {globalState.isSelectable && (
        <StyledProductTableCell isSelect>
          <GenericCheckbox />
        </StyledProductTableCell>
      )}
      {children}
    </StyledProductTableRow>
  );
};

export {
  ProductTable,
  ProductTableHeader,
  ProductTableRow,
};


Solution

  • The Solution

    I ended up creating a custom hook to handle this instead. The core issue was that I was trying to rely on global state values that were not updated immediately. Instead, I created refs that matched the values I was dispatching to global state and checked against the refs instead.

    ProductTableStore.jsx (Global State file) import React from 'react';

    const initialState = {
      isLoading: true,
      isSelectable: null,
      isHeaderFixedOnScroll: null,
      isHeaderActivelyFixed: null,
      isAddToCartEnabled: null,
      productTableActiveWidth: null,
      addToCartData: null,
    };
    
    const reducer = (state, action) => {
      switch (action.type) {
        case 'setIsHeaderFixedOnScroll':
          return {
            ...state,
            isHeaderFixedOnScroll: action.isHeaderFixedOnScroll,
          };
        case 'setIsHeaderActivelyFixed':
          return {
            ...state,
            isHeaderActivelyFixed: action.isHeaderActivelyFixed,
          };
        case 'setProductTableActiveWidth':
          return {
            ...state,
            productTableActiveWidth: action.productTableActiveWidth,
          };
        default:
          throw new Error(
            `Unexpected or missing action type. Action type provided was: ${action.type}`
          );
      }
    };
    
    const ProductTableContext = React.createContext({});
    
    const ProductTableStore = () => {
      return React.useContext(ProductTableContext);
    };
    
    const ProductTableProvider = ({ children }) => {
      const [state, dispatch] = React.useReducer(reducer, initialState);
      return (
        <ProductTableContext.Provider value={[state, dispatch]}>
          {children}
        </ProductTableContext.Provider>
      );
    };
    
    export { ProductTableStore, ProductTableProvider };
    

    ProductTable.jsx

    const ProductTable = ({ heading, ariaLabel, children }) => {
      const [globalState, dispatch] = ProductTableStore();
    
      const ProductTableRef = React.useRef(null);
    
      const setIsHeaderActivelyFixed = (isHeaderActivelyFixed) => {
        dispatch({
          type: 'setIsHeaderActivelyFixed',
          isHeaderActivelyFixed,
        });
      };
    
      const setProductTableActiveWidth = (productTableActiveWidth) => {
        dispatch({
          type: 'setProductTableActiveWidth',
          productTableActiveWidth: `${productTableActiveWidth}px`,
        });
      };
    
      const useShouldHeaderBeFixed = (ref) => {
        if (!globalState.isHeaderFixedOnScroll) return;
    
        // keep mutable refs of values pertinent to the fixed header for the lifetime of the component
        const fixedState = React.useRef(null);
        const fixedWidth = React.useRef(null);
    
        const [shouldHeaderBeFixed, setShouldHeaderBeFixed] = React.useState(false);
    
        const calculateTablePosition = () => {
          if (!fixedState.current && isActivelyViewed(ref.current)) {
            setShouldHeaderBeFixed(true);
            fixedState.current = true;
          } else if (!!fixedState.current && !isActivelyViewed(ref.current)) {
            setShouldHeaderBeFixed(false);
            fixedState.current = false;
          }
        };
    
        const calculateTableWidth = () => {
          if (fixedWidth.current !== ProductTableRef.current.offsetWidth) {
            setProductTableActiveWidth(ProductTableRef.current.offsetWidth);
            fixedWidth.current = ProductTableRef.current.offsetWidth;
          }
        };
    
        const calculateTablePositionAndWidth = () => {
          calculateTablePosition();
          calculateTableWidth();
        };
    
        React.useEffect(() => {
          calculateTablePositionAndWidth();
        }, []);
    
        React.useEffect(() => {
          window.addEventListener('scroll', calculateTablePosition);
          window.addEventListener('resize', calculateTablePositionAndWidth);
          return () => {
            window.removeEventListener('scroll', calculateTablePosition);
            window.removeEventListener('resize', calculateTablePositionAndWidth);
          };
        }, [isActivelyViewed(ref.current)]);
    
        return shouldHeaderBeFixed;
      };
    
      // initiallize our custom hook
      const shouldHeaderBeFixed = useShouldHeaderBeFixed(ProductTableRef);
    
      // listen only to our custom hook to set global state for the fixed header
      React.useEffect(() => {
        setIsHeaderActivelyFixed(shouldHeaderBeFixed);
      }, [shouldHeaderBeFixed, globalState.isHeaderFixedOnScroll]);
    ...