Home > Software engineering >  outlet context prop does not exist on type
outlet context prop does not exist on type

Time:09-11

Im curious what am i doing wrong here? This looks quite weird, why does invoiceList not exist on type Invoice[] as im setting the type in Root component file and then destructuring the prop on useOutletContext hook??? Am i missunderstanding something or what?

    import { ReactElement, useEffect, useState } from "react";
    import { Outlet } from "react-router-dom";
    import { Bar } from "../../components/Bar/Bar";
    import { Invoice } from "../InvoiceList/InvoiceList.utils";
    
    type Props = {};
    
    const Root = (props: Props): ReactElement => {
      const [invoiceList, setInvoiceList] = useState<Invoice[]>([]);
    
      useEffect(() => {
        const fetchData = async () => {
          const response = await fetch("./data.json");
          const data = await response.json();
    
          setInvoiceList(data);
        };
    
        fetchData();
      }, []);
    
      return (
        <div>
          <Bar />
          <Outlet context={{ invoiceList }} />
        </div>
      );
    };
    import { ReactElement } from "react";
    import { useOutletContext } from "react-router";
    import styled from "styled-components";
    import { Invoice } from "./InvoiceList.utils";
    import { InvoiceListHeader } from "./InvoiceListHeader/InvoiceListHeader";
    import InvoiceListItem from "./InvoiceListItem/InvoiceListItem";
    
    type Props = {};
    
    const InvoiceList = (props: Props): ReactElement => {
      const { invoiceList } = useOutletContext<Invoice[]>(); //Property 'invoiceList' does not exist on type 'Invoice[]'.
    
      return (
        <div>
          <InvoiceListHeader />
          <List>
            {invoiceList.map((item) => {
              return (
                <InvoiceListItem
                  key={item.id}
                  item={item}
                  invoiceList={invoiceList}
                />
              );
            })}
          </List>
        </div>
      );
    };

issue

CodePudding user response:

The type arg you are passing to useContext is incorrect. You have defined it as Invoice[] but actually its { invoiceList: Invoice[] }.

 const { invoiceList } = useOutletContext<{ invoiceList: Invoice[] }>();

To avoid this sort of thing in future you could define a new type in some common file like type OutletContext = { invoiceList: Invoice[] } and then reuse it everywhere you need it.

Or you could make a new custom hook that basically just has the useOutletContext in it with the right type arg, then return it. That way, you won't end up doing it lots of times.

  • Related