3

Data is coming back successfully from the API. This is my first time calling an API using TypeScript. The problem I am having is that I am not sure if my interface successfully verifies the API data or not.

const App = () => {
  const [userData, setUserData] = useState<User[]>([])
  console.log('User data: ', userData);

  useEffect(() => {
    axios
      .get<User[]>('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        setUserData(response.data)
      })
      .catch(error => console.log(error.message))
  }, [])

  return ...
};

export default App;

Here is my interface

export interface User {
  id: number,
  name: string,
  username: string,
  email: string,
  address: Address,
  phone: string,
  website: string,
  company: Company,
}

export interface Address {
  street: string,
  suite: string,
  city: string,
  zipcode: string,
  geo: Geolocation,
}

export interface Geolocation {
  lat: string,
  lng: string,
}

export interface Company {
  name: string,
  catchPhrase: string,
  bs: string,
}

1
  • 1
    See similar issue for typechecking during run time. Commented Dec 30, 2020 at 5:33

1 Answer 1

1

If you not sure about your props in interface has data or not. You could use this syntax interface your_interface_name { your_props_name?: type_data }

ex: export interface Geolocation { lat?: string, lng?: string, }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.