Search code examples
reactjstypescriptreact-tsxreact-typescript

Converting from React.js to React.tsx Property 'id' does not exist on type 'never'. TS2339


I am trying to follow a tutorial to learn react in type script. However when I build my solution I get and error. Code

import React, { useState, useEffect } from 'react';
import axios from 'axios';


const DataFetching = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(res => {
        console.log(res)
        setPosts(res.data)
      })
      .catch(err => {
        console.log(err)
      })
  })
  return (
    <div>
      <ul>
        {posts.map(post => (<li key={post.id}>{post.title}</li>))}
      </ul>
    </div>
  );
};

export default DataFetching;

the error I am getting

TypeScript error in src/DataFetching.tsx(21,43):
Property 'id' does not exist on type 'never'.  TS2339

I am following the following tutorial https://www.youtube.com/watch?v=bYFYF2GnMy8 . Any help or guidance is appreciated


Solution

  • You should always specify the type of the state variable. In this case, you are using an array of Posts. So you must create a Post interface and use that type in useState.

    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    
    interface Post {
      id: number;
      title: string;
    }
    
    const DataFetching = () => {
      const [posts, setPosts] = useState<Post[]>([]);
    
      useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/posts')
          .then(res => {
            console.log(res)
            setPosts(res.data)
          })
          .catch(err => {
            console.log(err)
          })
      })
      return (
        <div>
          <ul>
            {posts.map(post => (<li key={post.id}>{post.title}</li>))}
          </ul>
        </div>
      );
    };
    
    export default DataFetching;