Jump to content

Using Custom Hook Inside Callback Function (ReactJS)

theereal

So, ive got a custom hook that looks like this:

 

export default function useFetch(path) {

       
    const [array, setArray] = useState([]);
 
            useEffect(() => {
        axios.get(`${path}`)
            .then(res => {
                setArray(res.data)
            })
            .catch(err => {
                console.log(err)
            })
    },[])
 
    return array
 
}

 

I get the array in the main component by calling it like so:
<const gamesArr = useFetch(gameControllerUrl)>

 

 
However, theres also a delete function in the main component, and when someone deletes something id like to update state, i tried doing it like so:
useEffect(() => {
            useFetch(gameControllerUrl)
        },[deleteGameFlag])
 
 
However, im not allowed to use a custom hook inside a callback. Is there any way around this? To fetch the data using this custom hook and also updating state using the dependency array?
Link to comment
Share on other sites

Link to post
Share on other sites

You could try pass optional array of dependencies to your custom hook.

 

Untested:

const useFetch = (path, deps) => {
    const [array, setArray] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            const res = await axios.get(path);
            setArray(res.data);
        };

        fetchData();
    }, deps || []);

    return array;
};

 

React team suggests something different:

const useFetch = callback => {
    const [array, setArray] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            const res = await axios.get(path);
            setArray(res.data);
        };

        fetchData();
    }, [callback]);

    return array;
}

const data = useFetch(useMemo(() => {}, [your, deps, here]));

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×