79089880

Date: 2024-10-15 12:21:43
Score: 0.5
Natty:
Report link

Hi as far as I understand your question I would use a type to specify the ids. It seems you're using Types already. So defining ids as a Tuple might solve that issue. With this Type you can enforce that the provided Ids are always exactly two numbers; no more no less.

type Ids = [number, number];
type AppProps = {
  ids: Ids
}

const App = ({ids}: AppProps) => {
  const [data, setData] = useState<Record<number, Record[]>>({});
  useEffect(() => {
    const callAPI = async () => {
      ids.forEach(id => {
        const result = await axios.post("example.com", {id});
        setData((prev) => ({
          ...prev,
          [id]: result ?? [],
        }));
      })
    }
    callAPI()
  })
}

If you want to allow 0-2 ids you can make the numbers optional with "?"

type Ids = [number?, number?]

const value: Ids = [] // valid
const value1: Ids = [2] // valid
const value2: Ids = [2, 3] // valid
const value3: Ids = [2, 3, 4] // invalid
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Jannes