"Property does not exist on type 'never'" when i try to access a json data from API response

Viewed 334

When I try to access items fields like id or title it says Property does not exist on type 'never'.

BTW I can see the data properly when log it using console.log(response.data). I followed a tutorial, and it worked fine in the tutorial.

const [items, setItems] = useState([]);

    useEffect(() => {
        axios.get("https://jsonplaceholder.typicode.com/posts")
            .then(response => {
                setItems(response.data);
            })
            .catch(error => { console.log(error) })
    });

{items.map((item) => {
     <li key={item.id}>{item.title}</li>
})}
1 Answers

You need to provide an interface/type for the items:

interface Item {
  id: number
  title: string
}
const [items, setItems] = useState<Item[]>([]);

// OR

const [items, setItems] = useState<any[]>([]); // Do this if you don't want to write an interface or type

useState accepts a generic and returns the stateful value (of the type provided) and a function (which accepts the same type) to update the state value.

When we don't provide any generic to useState, it returns value and function but with a type knows as never.

And that's why you are seeing error:

properties (id and title) don't exist on type never

Related