0

I'm trying to build a section of my site that will dynamically pull in contact information from a REST API. At this point I'm using the sample API from https://jsonplaceholder.typicode.com.

I'm trying to use axios, specifically the useAxios and makeUseAxios hooks, to fetch the API, and store it in an app context that I can then use throughout the site, preferably with the useContext hook. Additionally, I'm needing to be able to update the API call based on user interactions, allowing them to select a location, have the API update, and store that in the app's context so that it all updates dynamically.

Essentially, I've gotten a basic useContext scenario working based on this tutorial, but I am struggling with how to store the JSON response in such a way that I can reference it in useContext. Here's the closest thing I've had going so far:

AppContext.tsx

import React, { createContext, ReactNode } from 'react';

import axios from 'axios';
import { makeUseAxios } from 'axios-hooks';
import { useCookie } from 'hooks/use-cookie';

export const AppContext = createContext();

export const DealerContextProvider = ({children}: any) => {
  const useAxios = makeUseAxios({
    axios: axios.create({ baseURL: 'https://jsonplaceholder.typicode.com/users/' }),
  });

  const LOCAL_STORAGE_KEY_DEALER = '_selectedDealerInformation';

  const [cookie] = useCookie('one-day-location', '1');
  const [dealerInfo] = useAxios(`${cookie}`);

  return (
    <AppContext.Provider value={[dealerInfo]}>
      {children}
    </AppContext.Provider>
  );
};

And my header component, where I'm trying to access it:

import React, { ReactNode, useEffect, useState, useContext } from 'react';

import { AppContext } from 'components/app-context/AppContext';

import Logo from 'assets/svg/logo.svg';
import css from 'classnames';
import { Button } from 'components/button/Button';
import { Link } from 'components/link/Link';

import { NotificationBar } from '../notification-bar/NotificationBar';
import s from './Header.scss';
import { MenuIcon } from 'components/menu-icon/MenuIcon';
import { MainNav } from './navigation/MainNav';

interface HeaderProps {
  navigationContent: ReactNode;
}

export const Header = ({ navigationContent }: HeaderProps) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  const blogInfo = useContext(AppContext);
  const buttonLabel = blogInfo ? `${blogInfo.name}` : 'Find a Dealer';
  const buttonLink = blogInfo ? `tel:${blogInfo.name}` : '/find-a-dealer';

  useEffect(() => {
    const handleScroll = () => {
      const isScrolled = window.scrollY > 10;
      if (isScrolled !== scrolled) {
        setScrolled(!scrolled);
      }
    };

    document.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      document.removeEventListener('scroll', handleScroll);
    };
  }, [scrolled]);

  return (
    <>
      <NotificationBar notificationContent={navigationContent} />
      <header
        className={scrolled ? css(s.header, s.header__scrolled) : s.header}
        data-open={open ? 'true' : ''}
      >
        <nav className={s.header__navigation}>
          <ul className={s.header__container}>
            <li className={s.header__logo}>
              <Link to="/" className={s.header__link}>
                <Logo />
              </Link>
            </li>

            <li className={s.header__primary}>
              <MainNav navigationItems={navigationContent} />
            </li>

            <li className={s.header__utility}>
              <Button href={buttonLink}>{buttonLabel}</Button>
            </li>

            <li className={s.header__burger}>
              <MenuIcon onClick={() => setOpen(!open)} />
            </li>
          </ul>
        </nav>
      </header>
    </>
  );
};

What I'm needing is for the button in header__utility to dynamically display the name and phone number of the chosen dealer. I can clarify anything as needed, I'm newish to React and am still learning how to express all that I'm needing.

Thanks!

Jesse Winton
  • 568
  • 10
  • 33

1 Answers1

0

Alright, I did a ton of digging over the last 24 hours, and I was able to find a solution.

I've got my context, now named ApiContext for clarity.

ApiContext.tsx

import React, { createContext } from 'react';

import axios from 'axios';
import { makeUseAxios } from 'axios-hooks';
import { useCookie } from 'hooks/use-cookie';

const contextObject = {} as any;

export const context = createContext(contextObject);

const useAxios = makeUseAxios({
  axios: axios.create({ baseURL: process.env.GATSBY_API_ENDPOINT }),
});

export const ApiContext = ({ children }: any) => {
  const [cookie] = useCookie('one-day-location', '1');

  const [{ data }] = useAxios(`${cookie}`);

  const { Provider } = context;
  return <Provider value={data}>{children}</Provider>;
};

Then, to use it across components, I wrap my AppLayout in <ApiContext>:

AppLayout.tsx

import React, { ReactNode } from 'react';

import { ApiContext } from 'contexts/ApiContext';
import { graphql, StaticQuery } from 'gatsby';

import { Devtools } from '../devtools/Devtools';
import { Footer } from '../footer/Footer';
import { Header } from '../header/Header';
import s from './AppLayout.scss';

interface AppLayoutProps {
  children: ReactNode;
  location: string;
}

const isDev = process.env.NODE_ENV === 'development';

// tslint:disable no-default-export
export default ({ children }: AppLayoutProps) => {
  return (
    <StaticQuery
      query={`${NavQuery}`}
      render={(data) => (
        <>
          <ApiContext>
            <Header navigationContent={data.prismic.allNavigations.edges[0].node} />

            <div className={s.layout}>
              {children}

              <Footer navigationItems={data.prismic.allNavigations.edges[0].node} />

              {isDev && <Devtools />}
            </div>
          </ApiContext>
        </>
      )}
    />
  );
};

const NavQuery = graphql`
  query NavQuery {
    prismic {
      allNavigations {
        edges {
          node {
            ...NotificationBar
            ...NavigationItems
            ...FooterNavigationItems
          }
        }
      }
    }
  }
`;

And in my Header component I can access the data with the useContext hook:

Header.tsx

import React, { ReactNode, useContext, useEffect, useState } from 'react';

import Logo from 'assets/svg/logo.svg';
import css from 'classnames';
import { Button } from 'components/button/Button';
import { Link } from 'components/link/Link';
import { MenuIcon } from 'components/menu-icon/MenuIcon';
import { context } from 'contexts/ApiContext';

import { NotificationBar } from '../notification-bar/NotificationBar';
import s from './Header.scss';
import { MainNav } from './navigation/MainNav';

interface HeaderProps {
  navigationContent: ReactNode;
}

export const Header = ({ navigationContent }: HeaderProps) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  const data = useContext(context);

  console.log(data);

  const buttonLabel =  data ? data.name : 'Find a Dealer';
  const buttonLink = data ? `tel:${data.phone}` : '/find-a-dealer';

  useEffect(() => {
    const handleScroll = () => {
      const isScrolled = window.scrollY > 10;
      if (isScrolled !== scrolled) {
        setScrolled(!scrolled);
      }
    };

    document.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      document.removeEventListener('scroll', handleScroll);
    };
  }, [scrolled]);

  return (
    <>
      <NotificationBar notificationContent={navigationContent} />
      <header
        className={scrolled ? css(s.header, s.header__scrolled) : s.header}
        data-open={open ? 'true' : ''}
      >
        <nav className={s.header__navigation}>
          <ul className={s.header__container}>
            <li className={s.header__logo}>
              <Link to="/" className={s.header__link}>
                <Logo />
              </Link>
            </li>

            <li className={s.header__primary}>
              <MainNav navigationItems={navigationContent} />
            </li>

            <li className={s.header__utility}>
              <Button href={buttonLink}>{buttonLabel}</Button>
            </li>

            <li className={s.header__burger}>
              <MenuIcon onClick={() => setOpen(!open)} />
            </li>
          </ul>
        </nav>
      </header>
    </>
  );
};

I'm still working on additional optimizations, specifically eliminating a flicker when loading in a page, and also updating the API on a button click, utilizing useCookie, which is a custom hook I've built out. Hopefully this gives some clarity to anyone else searching for this info, it took me hours and hours to determine a solution. Cheers.

Jesse Winton
  • 568
  • 10
  • 33