3

Goal:
Display the picture from API by the code that is used at the local hobby project in my local computer.

Problem:
When I use the code from stackblitz to the local computer I get a error about

TS2339: Property 'avatar_url' does not exist on type 'never'.

TS2339: Property 'login' does not exist on type 'never'.

However, when the same code is used in the stackblitz it works. In other words, it is the same code that is used for stackblitz and local project but it doesn't work in local development computer

What part am I missing in order to the code to be working in my local computer?

Stackblitz:
https://stackblitz.com/edit/react-ts-dah6xw?

Info:
Newbie in react TS

Thank you!

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

interface AppProps {}
interface AppState {
  name: string;
}

const apiUrl = 'https://api.github.com/users';

function App() {
  const [items, setItems] = React.useState([]);

  React.useEffect(() => {
    async function fetchData() {
      var data = await fetch(apiUrl).then((res) => {
        return res.json();
      });
      //console.log(data);
      setItems(data);
      console.log(data);
    }
    fetchData();
  }, []);

  return (
    <div>
      {items.map((item) => (
        <div>
          <img src={item.avatar_url} />
          <div>{item.login}</div>
        </div>
      ))}
      ;
    </div>
  );
}

render(<App />, document.getElementById('root'));

enter image description here

enter image description here

1
  • 1
    DO NOT post images of code, data, error messages, etc. - copy or type the text into the question. How to Ask
    – Rob
    Dec 30, 2021 at 22:39

1 Answer 1

1
+50

Try to give type to useState() like:

type User = {
  avatar_url: string;
  login: string;
};

///
const [items, setItems] = React.useState<User[]>([]);

I guess your config is very aggressive for linting and TS errors. Normally React doesn't show such errors while compiling.

1
  • It works. Thank you for your help! Dec 30, 2021 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.