简体   繁体   中英

Why does this custom hook return indefined in react?

i am creating a custom hook in React, this is my code:

import {useEffect} from 'react';

const useFetch = (url) => {
    useEffect(() => {
        const fetchData = () => {
            const data = url + "TEST";
            return data;
        }
        fetchData();
    })
}

export default useFetch;

It now returns some dummy value but that is just because of testing purposes.

Here is where i invoke my custom hook:

const Data = useFetch("https://customapiurlrandom.com/");
 useEffect(() => {
 console.log(Data);
}, [])

The thing is, when i check my console i see undefined . And i can't find out why.

Any ideas? Thanks in advance.

Your custom hook didn't return anything. You should add a state to keep the value and return it

import {useEffect, useState} from 'react';

const useFetch = (url) => {
    const [data, setData] = useState(null);

    useEffect(() => {
        const fetchData = () => {
            const data = url + "TEST";
            return data;
        }
        setData(fetchData());
    },[url, setData]);

    return data;
}

export default useFetch;

And then use like this

const Data = useFetch("https://customapiurlrandom.com/");
useEffect(() => {
    console.log(Data);
}, [Data])

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