juha
juha

Reputation: 595

React with Typescript: Argument of type 'never[]' is not assignable to parameter of type 'StateProperties | (() => StateProperties)'

I am practicing typescript. For the backend, I used node express typescript and for the frontend, I used react typeScript. I fetched the data from the backend and try to render it on my browser. I am getting an error: property 'name' does not exist on type 'never'. TS2339. I think this error is coming from typescript. This is the error visualization

This is my backend setup

import express = require("express");
import cors = require("cors");
const app = express();
app.use(cors());
const port = 8080;
app.get("/", (req, res) =>
  res.send([
    {
      name: "John",
      age: 36
    },
    {
      name: "alex",
      age: 27
    }
  ])
);

app.listen(port, () => console.log(`server running port ${port}`));

This is is my React component

    import React, { useEffect, useState } from "react";

interface StateProperties {
  name: string;
  age: number;
}

//StateProperties | (() => StateProperties)
function App() {
  const [state, setState] = useState<StateProperties>([]);

  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    const response = await fetch("http://localhost:8080/");
    const data = await response.json();
    console.log(data);
    setState(data);
  };

  return (
    <div className="App">
      {state.length}

      {state.map((list, index) => {
        return <li key={index}>{list.name}</li>;
      })}
    </div>
  );
}

export default App;

Upvotes: 19

Views: 21818

Answers (1)

wentjun
wentjun

Reputation: 42526

You need to provide the interfaces/type aliases so that TypeScript will know the typings of state.

After creating the interface for state, you will need to provide the interface as the generics for useState.

To solve the 2nd issue, you will need to provide the key props to each item of the <li> element

interface StateProperties {
  name: string;
  age: number;
}

function App() {
  const [state, setState] = useState<StateProperties[]>([]);

  // do the rest

return (
  <div className="App">
    {state.map(({ name, age }) => {
      return <li key={`${name}-${age}`}>{name}</li>; //FROM HERE ERROR IS COMING
    })}
  </div>
  );

}

Upvotes: 39

Related Questions