Home > Enterprise >  How to a function of another class in React?
How to a function of another class in React?

Time:04-14

I am noob on front-end world and could not find a solution for that I have a MainPanel component and I want to get data by using a service class method. The service class will have multiple functions and I will use them in different places.

Here is MainPanel code:

  const [posts, setPosts] = useState({ blogs: [] });

  const service = FetchCustomerService;

useEffect(() => {
    const fetchPostList = async () => {
      let customers = service.getCustomerList;
      setPosts({ customers });
      console.log(customers);
    };
    fetchPostList();
  }, []);

And I want to create a separate service class for calls to backend:

export class FetchCustomerService {


    getCustomerList = () => {
        const { data } = await axios(
            "https://jsonplaceholder.typicode.com/posts"
          );
          return data;
    }

    getAnotherFunction = () => {

    }
}

export default FetchCustomerService;

How can I call service class method from MainPanel? There are some examples like giving the service class into main panel as props but isn't it possible to just call it like a Java class object etc calling like:

FetchCustomerService.getCustomerList();

CodePudding user response:

You don't need a class for that, just export the functions you need from the file:

export async function getCustomerList() {
    const { data } = await axios(
       "https://jsonplaceholder.typicode.com/posts"
    );
    return data;
}

export function getAnotherFunction(){
  ...
}
import { getCustomerList } from 'yourFile';

...

useEffect(() => {
    const fetchPostList = async () => {
      const customers = await getCustomerList();
      setPosts({ customers });
    };
    fetchPostList();
  }, []);
  • Related