skip to Main Content

I have a state and use it as index of array of objects. And When I pass that object into other components as props. It gives an Error even though there’s checking:

import React, { Dispatch, useState } from 'react';

import { TestingTwo } from './TestingTwo';

interface Menu {
  ItemNumber?: number;
  ItemString?: string;
  setState?: Dispatch<React.SetStateAction<number>>;
}

export const TestingPage = () => {
  const [activeMenu, setActiveMenu] = useState<number>(1);
  const [something, SetSomething] = useState<number>(0);
  const TestMenu: Menu[] = [
    {
      ItemNumber: 1,
      ItemString: 'test',
      setState: SetSomething,
    },
  ];
  return (
    <>
      {TestMenu && TestMenu[activeMenu] && TestMenu[activeMenu].ItemNumber ? (
        <TestingTwo
          number={TestMenu[activeMenu].ItemNumber || 0}

          OnClick={() => TestMenu[activeMenu].setState(1)}
//Cannot Invoke an object which is possibly 'undefined'

        />
      ) : null}
    </>
  );
};

The component:

interface TestingTwoProps {
  number: number;
  OnClick: () => void;
}

export const TestingTwo = ({ number, OnClick }: TestingTwoProps) => {
  return <>{number}</>;
};

2

Answers


  1. Chosen as BEST ANSWER

    I have found a workaround for this. But I don't understand why do I have to use a tempFunc to store the setState function first. Can anyone kindly explain to me?

    <>
          {TestMenu && TestMenu[activeMenu] && TestMenu[activeMenu].ItemNumber ? (
            <TestingTwo
              number={TestMenu[activeMenu].ItemNumber || 0}
              OnClick={() => {
                const tempFunc = TestMenu[activeMenu]?.setState;
                if (tempFunc) {
                  tempFunc(1);
                }
              }}
            />
          ) : null}
        </>
    

  2. There’s three solutions here:

    1. Update the type of number in TestingTwo to number | undefined.

    2. The other solution is:

      <TestingTwo number={TestMenu[activeMenu].ItemNumber ?? 0} />

    3. (Recommended if you know number will always be required) update your interface from:

      interface Menu { ItemNumber?: number; ItemString?: string; }
      to:

      interface Menu { ItemNumber: number; ItemString?: string; }

    Removing the optional ? on ItemNumber

    UPDATE FOR SECOND QUESTION

    You have the same issue on set state where the interface has it as an optional field.

    1. You make it required by removing the ?

    2. OnClick={() => TestMenu[activeMenu]?.setState() < update to that where you have a question mark checking if setState exists

    FINAL EDIT

    To get the final bit you need just add the following:

    OnClick={() => TestMenu[activeMenu]?.setState(1)

    The reason for you error is you were not passing a value to setState

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search