Kousalya
Kousalya

Reputation: 760

How to use functions from another component in React Typescript

I have two components, one for API and another for UI. I am trying to access a function from API Component in UI component like below,

import APIComponent "./APIComponent";
APIComponent.getData().(response:any) => { //showing error here as "Property 'getData' does not exist on type '{ APIComponent: () => any; }'"
    console.log(response);
  })

Below is my APIComponent,

const APIComponent=():any=>{
const getData=():any =>{
//forming request
}
}

Thanks in Advance.

Upvotes: 2

Views: 1348

Answers (1)

Yaya
Yaya

Reputation: 4838

You should export them first, without an default export, so that would be

export const APIComponent=():any=>{}
export const getData=():any =>{}

Then try to import them

import {getData} "./APIComponent";

or try to export default and object and in that object add the functions as methods like so

export const APIComponent = () => {};
const getData = () => {
  alert("Getting the data");
};
export default {
  getData
};

Then you can actually export them and import them without the Destructure Syntax

import APIComponent from "./APIComponent"

   APIComponent.getData();

Have a look at this Sandbox https://codesandbox.io/s/morning-feather-9z24o?file=/src/App.js

Upvotes: 1

Related Questions