Theres some questions about the same error here but i tried a few solutions that didnt end up working for me so i will try asking showing my situation, heres my code:
const[ enquetes, setEnquetes ] = useState([])
api.get('/polls/b44a0040-5201-4f0e-ba68-2b51545d5276').then( (response) => {
setEnquetes(response.data)
console.log(enquetes.title)
})
So im integrating a node server with a react typescript app. In the code above i got the informations from the server and stored in "enquetes" using useState. When i try to console.log(enquetes) it works fine, but when i try using "title" that is an existing property in the server or any other property, i get the error "Property does not exist on type never[]".
I already tried: useState<any[]>([]) in the const; console.log(enquetes[‘title’] and some other things but none worked, anyone can spot what should be done?
2
Answers
You havn’t specified what type this state is, so typescript has to try to infer it. You passed in an array with no contents, so the best typescript can do is infer a
never[]
. Arrays do not have a.title
property, soenquentes.title
is not allowed.useState
is a generic, and you can pass in what type you want the state to be. I’d recommend you use something likenull
to represent the fact that you’re still loading instead of an array, since it’s easier to check for null. For example:When you want to use
enquentes
, do so something like this:I can see two possible answers to your problem.
1. Object or Array
In the declaration of the useState, the default value is an empty array, so I assume that the response from the get request from api should be also an array of objects.
If this is the case, the right way to display the property title from the response should be something like this:
Because an array is a collection of informations, can be an object like your case or a primitive like strings or numbers, and for you access this informations you need
specify the place you want, so that is why you put 0.
2. Accessing your object wrong
In the exemple of the response from the get, your object is poll: { id: string, title: string, options: array }.
For display the property title correctly you need acess the object poll before, like this:
I hope some of this answers help you.