0

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();

1
  • 1
    You can use and export them as function itselfs. I would say just create service.ts file and export them from there Commented Apr 13, 2022 at 20:42

1 Answer 1

4

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();
  }, []);
Sign up to request clarification or add additional context in comments.

3 Comments

Note you can use {transformResponse} config so you don't have to unwrap .data every time you make an axios request
additional note, you should fetchPostList().catch(...) to handle errors and avoid unhandled promise rejection warning.
the answer is worked thanks. But if I put console.log(customers) just under setposts in useeffect then it is writing to console twice. How can I just execute that part only once?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.