First of all, I would like to mention that although this question has been asked several times before, none of the solutions seem to work for me.
Basically, I am using Ionic React, and at one point in my code, I have an Object which I declare as:
const [allArrays, setAllArrays] = useState<AllArraysObject>({});
AllArraysObject
is a custom type which is declared in another file as:
export interface myType{
a: number,
b: string,
...
}
export type AllArraysObject= {
[key: string]: myType[]
}
What I actually expect to create is an object which looks like this:
{
"1": [
{a: 10, b: "Hello", ...},
{a: 11, b: "Hi", ...},
...
],
...
}
which is essentially an Object of Arrays of Objects . The Issue is that I cannot use Object.keys(AllArrays)
to get an array of all the keys of the object (like ["1", "2", ...]
). I have used the same method previously in the application when it worked perfectly fine (at that point, I had an Object of objects ).
I have tried the following:
Object.keys(allArrays)
Object.keys(allArrays as Object)
Object.keys(JSON.parse(JSON.stringify(allArrays)))
Object.getOwnPropertyNames(allArrays)
each of which returns me an empty Array(0)
. As expected, if I console.log(allArrays)
, I can see all the properties of the object, and on running the above-mentioned functions in the console, I do get the desired output.
I wish to know what mistake I am committing here (which could possibly be because of a gap in my understanding of how Objects work) and I also seek an explanation of the above behavior. Any help would be deeply appreciated.
Remember that useState has an initial value, in this case it's an empty object {}
. I would assume you are logging the values before they are set.
const Component = () => {
const [allArrays, setAllArrays] = useState<AllArraysObject>({});
useEffect(() => {
const sampleObject = { "1": [ { a: 10, b: "Hello" }, { a: 11, b: "Hi" } ] }
setAllArrays(sampleObject);
}, [])
console.log(Object.keys(allArrays))
// This be Array(0) on mount until setAllArrays is set
// when useEffect issues a side-effect
// so make a guard if object is empty
if (Object.keys(allArrays).length === 0 && obj.constructor === Object) {
// null else set to anything you desire
return null;
}
return (
<div>{/* use allArrays */}</div>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.