简体   繁体   中英

Using a custom hook in useEffect

I am trying to use a custom Axios hook to fetch some data but I get an error that says 'invalid hook call. Hooks can only be called inside the body of a function component.' I know this sounds obvious but to a neewb this doesn't make that much sense.

Here is the hook:

import { useState } from "react";
import axios from "axios";

export default useApi = () => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);

  const request = async () => {
    const source = axios.CancelToken.source();
    setLoading(true);

    try {
      const response = await axios.get(url, { cancelToken: source.token });
      setData(response.data);
      setLoading(false);
    } catch (error) {
      if (axios.isCancel(error)) {
        // don't update state in case component is dismounting
        console.log("cancelled");
      } else {
        setLoading(false);
        setError(error);
      }
    }

    return () => {
      source.cancel();
    };
  };

  return { data, error, loading, request };
};

I want to be able to use data, error, loading and request just like returned so I tried to use destructuring.

import React, { useEffect } from "react";
import useApi from "../hooks/http-hook";
const { request, data, error, loading } = useApi();


const SomeComponent = (props) => {

    useEffect(() => {
      const getUsers = async () => {
        try {
          const res = await request("http://localhost:8000/api/users");
          console.log(res);
        } catch (err) {
          console.log(err);
        }
      };
      getUsers();
    }, [request]);
}

export default SomeComponent;

You have to use your hook inside a component.

I see you are trying to call it just behind the import, and I suppose that is outside any kind of component. Try something like

import useApi from "../hooks/http-hook";

const YourComponent = () => {
    const { request, data, error, loading } = useApi();
    console.log(request, data, error, loading);
    return <Stuff/>
}

    

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