juha
juha

Reputation: 595

Typescript: property "title" does not exist on type 'never'

I am practicing React-native typescript. I fetched the data from jsonplaceholer API and added to my component state. After mapping the state and try to render on my mobile. But I am getting typescript error on my terminal: property "title" does not exist on type 'never'.

This is my app component

import React, { useState, useEffect } from "react";
import { StyleSheet, Text, View, ScrollView, Image } from "react-native";

export default function App() {
  const [state, setstate] = useState([]);

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

  const fetchData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/photos");
    const data = await response.json();
    setstate(data);
  };

  return (
    <ScrollView style={styles.body}>
      <View style={styles.container}>
        {state.map(list => {
          return <Text>{list.title}</Text>; //
        })}
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  body: {
    padding: 150
  },
  container: {
    flex: 1,
    backgroundColor: "white",
    alignItems: "center",
    justifyContent: "center"
  },

  stretch: {
    width: 50,
    height: 200,
    resizeMode: "stretch"
  }
});

Upvotes: 5

Views: 30664

Answers (1)

Rashomon
Rashomon

Reputation: 6762

You have to define your state as an array of any type:

const [state, setstate] = useState([] as any[]);

By default, TypeScript defines empty arrays ([]) as type never[]. That is an array that always will be empty. A bizarre thing of TS. More info in this question.

Upvotes: 26

Related Questions