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?
const[ enquetes, setEnquetes ] = useState([])
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, so enquentes.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 like null
to represent the fact that you're still loading instead of an array, since it's easier to check for null. For example:
type Data {
poll: {
id: string;
title: string;
options: unknown[]; // fill this in with an appropriate type. I can't tell from your post.
}
}
// ...
const [enquentes, setEnquentes] = useState<Data | null>(null);
// ...
api.get('/polls/b44a0040-5201-4f0e-ba68-2b51545d5276').then( (response) => {
setEnquetes(response.data)
console.log(response.data.poll.title)
// there is no point in logging `enquentes` here, since it is null
})
When you want to use enquentes
, do so something like this:
return (
<div>
{enquentes ? (
<span>{enquentes.poll.title}</span>
) : (
<div>Loading...</div>
)}
</div>
)