Reputation: 120
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.
Upvotes: 0
Views: 53
Reputation: 181
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])
Upvotes: 2