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

Chris Garsonn
  • 717
  • 2
  • 18
  • 32
  • 1
    You can use and export them as function itselfs. I would say just create service.ts file and export them from there – Evren Apr 13 '22 at 20:42

1 Answers1

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();
  }, []);
moonwave99
  • 21,957
  • 3
  • 43
  • 64
  • Note you can use `{transformResponse}` [config](https://axios-http.com/docs/req_config) so you don't have to unwrap `.data` every time you make an axios request – Mulan Apr 13 '22 at 20:41
  • 1
    additional note, you should `fetchPostList().catch(...)` to handle errors and avoid [unhandled promise rejection warning](https://stackoverflow.com/questions/40500490/what-is-an-unhandled-promise-rejection). – Mulan Apr 13 '22 at 20:42
  • 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? – Chris Garsonn Apr 13 '22 at 20:45