React: Using state as index into array of objects returns undefined despite checking
P粉481035232
P粉481035232 2024-04-03 14:12:42
0
1
403

I have a state and use it as an index into an array of objects. When I pass that object as a prop to other component. Even with the check, it gives the error:

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}
    </>
  );
};

Components:

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

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

reply all(1)
P粉642920522

Here are three solutions:

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

  2. Another solution is:

  3. (Recommended if you know you will always need the number) Update your interface from:

    interface menu { ItemNumber?: number;Item string? : string; } to:

    Interface menu {ItemNumber: number;Item string? : String; }

Remove optional on ItemNumber ?

Update second question

You also encounter the same problem in setting the status, the interface makes it an optional field.

  1. You can make it required by removing ?

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

Final Edit

To get the last bit, you just add the following:

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

The reason for the error is that you are not passing a value to setState

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template