I am trying to set up a custom hook that fetches data, does some manipulations on the data and returns the manipulated data in a react d3 application. The data type is
interface EventViewerDataTypes {
date: string
site: string
type: string
value: string
}[]
Inside the useEffect hook there is an error Object is of type 'unknown'.
import { useState, useEffect } from "react"
import { json, timeParse } from "d3"
const parseTime = timeParse("%d-%m-%Y")
interface EventViewerDataTypes {
date: string
site: string
type: string
value: string
}[]
export const useData = (jsonUrl: string) => {
const [data, setData] = useState<EventViewerDataTypes | null>(null)
useEffect(() => {
json(jsonUrl).then((data) => {
data.forEach((d) => {
d.date = parseTime(d.date)
d.value = +d.value
})
setData(data)
})
}, [])
return data
}
I'm a bit struggling with typescript and any help, or recommendations would be valuable.
Update
With the help of Robby Cornelissen, I made some progress and updated the code, and still some issues. So I tried updating the EventViewerDataTypes as
interface EventViewerDataTypes {
date: string | Date | null
site: string
type: string
value: string | number
}[]
But still have some errors
json<EventViewerDataTypes[]>(jsonUrl).then((data) => {
data?.forEach((d) => {
// Error!
d.date = parseTime(d.date)
// Argument of type 'string | Date | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'
d.value = +d.value
})
// Error!
//Argument of type 'EventViewerDataTypes[] | undefined' is not assignable to parameter of type 'SetStateAction<EventViewerDataTypes | null>'
setData(data)
})