Reputation: 1830
I am trying to pass a string value in a custom hook call to the hook file itself. For example, I have a json file I want to pass to a custom hook to get that data, however in my current implementation, I am getting an error of TS2345: Argument of type 'string' is not assignable to parameter of type '{ string: any; }'.
even when I specify the prop types. Why is this happening?
import axios from 'axios';
import React, { FC } from 'react';
import { useState, useEffect } from 'react'
interface APICallProps {
apiCall: string
}
const useFetchSecurityData = ({ string: apiCall }) => {
const [loading, setLoading] = useState<boolean>(true)
const [data, setData] = useState<null>(null)
useEffect(() => {
fetchData()
}, [])
const fetchData = async () => {
axios.get(apiCall)
.then(res => {
setData(res.data)
})
.catch(err => console.error(err))
setLoading(false)
}
return { data, loading }
}
export default useFetchSecurityData
const ChartArea = () => {
const [incidents, setIncidents] = useState([])
const { data, loading } = useFetchSecurityData('incidents.json')
// const { data, loading } = useFetchIncidents()
useEffect(() => {
fetchData()
}, [loading, data])
const fetchData = () => {
try {
let rawData = (data) ?? []
setIncidents(rawData)
} catch (err) {
console.error(err)
}
}
}
Upvotes: 0
Views: 2701
Reputation: 2379
{ string: apiCall }
is not the correct syntax for typing in this scenario.
{ string: apiCall }
is asking to destructure your props
for the component, and in props their should be a property called string
which you wish to alias as apiCall
.
Typing for a hook should look like one of the following:
interface MyReturnType {
data: any;
loading: boolean;
}
interface MyCustomHookFn {
(propA: string, propB: number, propC: Date) => MyReturnType
}
const useMyCustomHook: MyCustomHookFn = (propA, propB, propC) => {
...
}
OR
const useMyCustomHook = (propA: string, propB: number, propC: Date) => {
...
}
Previous examples for components retained just in case someone wants them.
Typing for a component should look something like:
import React, { FC } from 'react';
interface ExampleComponentProps {
apiCall: string
}
const ExampleComponent: FC<APICallProps> = ({ apiCall }) => {
...
}
OR
import React from 'react';
interface ExampleComponentProps {
apiCall: string
}
const ExampleComponent = ({ apiCall }: APICallProps) => {
...
}
Upvotes: 1