0

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.

4
  • Are you doing a fetch() inside of fetchData()? Your useFetch() doesn't return anything either Commented Mar 3, 2021 at 8:47
  • 1
    You're not returning anything. And you should use useState with useEffect Commented Mar 3, 2021 at 8:50
  • @NickParsons the final goal is to do a fetch inside fetchData indeed, how would i make my useFetch return FetchData(); ? Commented Mar 3, 2021 at 8:58
  • Exactly what @ritaj said. Check here for a complete example reactjs.org/docs/hooks-custom.html Commented Mar 3, 2021 at 8:58

1 Answer 1

2

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

1 Comment

Thanks for answering! This works. I find it so difficult working with normal logic inside React... because, why do i need state for this? State is used for the state of components right? And when de state changes the component re-renders. So why would state be needed here?

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.