Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks with typescript: Property 'data' does not exist on type

I have an error that makes no sense, I am typing the value of my state with hooks, but he says the error is not the same type.

Already tried with empty array and even array with some data and always error is the same.

import React, { useState } from 'react';
import { Row, Col } from 'config/styles';
import Bed from './Bed';

interface DataTypes {
  date: string;
  value: number;
}

function Beds(): JSX.Element {
  const { data, setData } = useState<DataTypes[]>([]);

  return (
    <>
      <Row>
        {data.map((d, i) => (
          <Col key={i} sm={16.666} lg={10}>
            <Bed {...d} />
          </Col>
        ))}
      </Row>
    </>
  );
}

export default Beds;

Erro this:

TypeScript error in /Users/keven/Documents/carenet/orquestra-frontend/src/Beds/index.tsx(11,11):
Property 'data' does not exist on type '[DataTypes[], Dispatch<SetStateAction<DataTypes[]>>]'
like image 774
Keven Jesus Avatar asked Sep 27 '19 19:09

Keven Jesus


People also ask

How to fix ‘property does not exist on type ‘detailedhtmlprops’ on react and typescript’?

to add the custom property into the HTMLAttributes interface. Then we can add the custom attribute into the HTML elements in our React project. To fix the "Property does not exist on type ‘DetailedHTMLProps, HTMLDivElement>’" error with React and TypeScript, we can extend the react module’s types using a declare statement.

Do you like hooks in typescript?

... I think hooks are exciting. I also think that TypeScript’s great generics and type inference features are a perfect match to make your hooks type safe, without doing too much. That’s TypeScript’s greatest strength: Being as little invasive as possible, while getting the most out of it.

How to solve property does not exist on type 'never' error?

The error "Property does not exist on type 'never'" occurs when we forget to type an array or don't type the return value of the `useRef` hook. To solve the error, use a generic to explicitly type the state array or the ref value in your React application.

Do I need typescript annotations for strong typing?

Our desire for strong typing is that values we initially set, get per component update, and set through events, always have the same type. With the provided typings, this works without any additional TypeScript: And that’s it. Your code works with out any extra type annotations, but still typechecks.


2 Answers

It should be an array, not an object:

const [data, setData] = useState<DataTypes[]>([]);

You have this indication in the error message:

type '[DataTypes[], Dispatch<SetStateAction<DataTypes[]>>]'
like image 171
laurent Avatar answered Oct 19 '22 06:10

laurent


you should use const [ data, setData ] instead of const { data, setData }

like image 30
Ihor Shtyka Avatar answered Oct 19 '22 06:10

Ihor Shtyka