简体   繁体   中英

How to pass an argument in a react custom hook in typescript?

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; }'. 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?

  1. Custom hook to dynamically call a JSON file for its data
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
  1. Implementation of custom hook on a page layout
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)
    }
  }
}

{ 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) => {
    ...
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM