1

I started out typescript with Ionic-react so i am facing typescript issue in setting my state

Here is my code

import { RouteComponentProps } from "react-router-dom";

type ICoord = {
  data: number[];
};
type Props = RouteComponentProps & ICoord;

const Verify: React.FC<Props> = ({ history }) => {
  const coordinates: number[] = [];
  const [data, setdata] = useState<ICoord>();

  useEffect(() => {}, [data]);
  const start = () => {
    navigator.geolocation.watchPosition(
      (data) => {
        console.log(data);
        coordinates[0] = data.coords.latitude;
        coordinates[1] = data.coords.longitude;
        setdata(coordinates);
      },
      (err) => {
        console.log(err);
      },
      { enableHighAccuracy: true }
    );
  };
  const stop = () => {};

  return (
    <div>
      <button onClick={start}>start</button>
      <button onClick={stop}>stop</button>
    </div>
  );
};

export default Verify;

so when i try to set state in the line

setdata(coordinates);

it gives me the error

Argument of type 'number[]' is not assignable to parameter of type 'SetStateAction<ICoord | undefined>'. Type 'number[]' is not assignable to type '(prevState: ICoord | undefined) => ICoord | undefined'.

Ratnabh kumar rai
  • 1,426
  • 4
  • 21
  • 48

2 Answers2

2
const [data, setdata] = useState<ICoord | undefined>();
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
1

just lose "ICoord" as you only have one value for it, you don't need to write more code. Also, in useState you can define the data type

const [data, setData] = useState([])
That Guy Kev
  • 386
  • 2
  • 10