I have a chart component in which specific lines can be shown/hidden. To keep track of which lines are active I keep an activeKeys array in a state. Initially I get the key names from a function getKeys that takes the array of data.
When I do this:
const defaultValue = getKeys(data)
console.log('defaultValue from keys', defaultValue)
const [activeKeys, setActiveKeys] = useState(defaultValue)
console.log('activeKeys', activeKeys)
First console log shows the correct keys:
["createdCount", "confirmedCount", "hasFeedbackCount"]
Second console log shows []
But if I do:
const defaultValue = ["createdCount", "confirmedCount","hasFeedbackCount"]
console.log('defaultValue', defaultValue)
const [activeKeys, setActiveKeys] = useState(defaultValue)
console.log('activeKeys', activeKeys)
First console log shows the same array:
["createdCount", "confirmedCount", "hasFeedbackCount"]
And activeKeys shows the correct array:
["createdCount", "confirmedCount", "hasFeedbackCount"]
Is useState broken or something? By the getKeys is a simple function, no promise or anything like that. It looks like this:
const getKeys = (data: Props['data']): string[] => {
const reduced = data.reduce((acc, datum) => [...acc, ...Object.keys(datum.lines)] as any, [])
const setted = new Set(reduced)
const arrayed = Array.from(setted)
return arrayed
}
The shape of Props['data'] is:
data: {
date: string
lines: Partial<Record<string, number>>
}[]