I tried to convert a nested object type to array for easy manipulation but somehow, got an undefined error when I did a console.log(datafour).
I believe the Typescript types are not defined correctly somewhere. Any help or hint would be greatly appreciated.
import { useEffect, useState } from 'react'
import _ from 'lodash'
interface DataProps {
id: number
clazz_name: string
answers: [{ emotion: number }, { emotion: number }]
created_at: string
}
const dataone: DataProps[] = [
{
id: 1,
clazz_name: '1A',
answers: [{ emotion: 3 }, { emotion: 9 }],
created_at: 'jan',
},
{
id: 2,
clazz_name: '1A',
answers: [{ emotion: 4 }, { emotion: 12 }],
created_at: 'feb',
},
{
id: 3,
clazz_name: '1B',
answers: [{ emotion: 2 }, { emotion: 10 }],
created_at: 'feb',
},
{
id: 4,
clazz_name: '1B',
answers: [{ emotion: 1 }, { emotion: 11 }],
created_at: 'feb',
},
]
const App = () => {
const [datafour, setDatafour] = useState<[string, DataProps[]][]>()
useEffect(() => {
const datatwo = _.groupBy(dataone, 'clazz_name')
console.log(datatwo)
const datathree: [string, DataProps[]][] = Object.entries(datatwo)
console.log(datathree)
setDatafour(datathree)
console.log(datafour). //undefined
}, [])
return <div>React Typescript</div>
}
export default App