My first attempt at a custom hook is now looping like crazy, I don't fully understand why do I need to test to see if it has something saved in response or error then make the call if it has not?
import React, { useContext } from 'react';
import { Context } from "../components/context";
const useFetch = (url: string, bearer: string, method: string, body: any) => {
const { global } = useContext(Context) as {global: any};
let headers = {'cache-control': 'no-cache', 'Content-Type': 'application/json' };
if (bearer) headers = {...headers, ...{'Authorization': bearer}}
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const apiUrl = global.apiUrl;
React.useEffect(() => {
const fetchData = async () => {
try {
let res;
if (method === 'GET') res = await fetch(apiUrl + url, {method, headers});
else res = await fetch(apiUrl + url, {method, headers, body});
setResponse(await res.json());
} catch (error) {
setError(error);
}
};
fetchData();
}, [apiUrl, body, headers, method, url]);
return { response, error };
};
export { useFetch }
I'm calling it with
import { useFetch } from '../hooks/fetch';
const res = useFetch('http://api.domain.com', '', 'GET', '')
console.log(res);
Each time you unconditionally change state in useEffects it will loop endlessly because it is calling after each state change, you change state again and again useEffects is calling and so on...
There should be some flag probably, and you fetch data only if flag is not true
const [isLoaded, setIsLoaded] = React.useState(false);
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const apiUrl = global.apiUrl;
React.useEffect(() => {
const fetchData = async () => {
if (isLoaded) return
try {
let res;
if (method === 'GET') res = await fetch(apiUrl + url, {method, headers});
else res = await fetch(apiUrl + url, {method, headers, body});
setResponse(await res.json());
setIsLoaded(true)
} catch (error) {
setError(error);
}
};
useEffect gets called anytime one of its dependencies changes. You put in [apiUrl, body, headers, method, url]. Both headers and apiUrl are local variables and recreated everytime the hook is called. This means that the references to those variables will change everytime your useFetch executes.
The useEffect sets a state on success or error which causes the re-render which causes the recreation of those variables which causes the useEffect to be called again.
I recommend removing both of those from the dependency array and moving the variables into your useEffect call as they are only used inside there anyways.
Related
I am trying to change the data every time, url_slug is changing but the data is not refreshing. getting the same data.
const [relatedSnippets,setrelatedSnippets] = useState([]);
const [loading,setLoading] = useState(false);
useEffect(async ()=>{
setLoading(true);
const snippetData = await getData(url_slug);
setrelatedSnippets(snippetData.snippets);
setLoading(false);
},[url_slug]);
async function getData(url_slug) {
var config = {
headers: {
accept: '*/*',
'Content-Type': 'application/json',
'API_ACCESS_KEY': 'hns2V0Ddbkkn8r1XLq3Kw7ZoiBTR0nmA',
}
};
const data = {
slug:url_slug,
}
const url = `http://localhost:8000/api/similarsnippets`;
const snippetData = await axios.post(url,data,config);
const finalData = snippetData.data;
return finalData;
}
The useEffect hook's callback needs to be a synchronous function. Move the async function into the callback and then invoke it.
useEffect(() => {
const loadData = async () => {
setLoading(true);
const snippetData = await getData(url_slug);
setrelatedSnippets(snippetData.snippets);
setLoading(false);
};
loadData();
}, [url_slug]);
I'm trying to get the data of "body" outside of the fetchUserData() function.
I just want to store it in an variable for later use.
Also tried modifying state, but didn't work either.
Thanks for your help :)
const [userData, setUserData] = useState();
async function fetchUserData () {
try {
const result = await fetch(`/usermanagement/getdocent`, {
method: "GET"
});
const body = await result.json();
//setUserData(body);
return(
body
)
} catch (err) {
console.log(err);
}
}
let userTestData
fetchUserData().then(data => {userTestData = data});
console.log(userTestData);
//console.log(userData);
Use useEffect
async function fetchUserData () {
try {
const result = await fetch(`/usermanagement/getdocent`, {
method: "GET"
})
return await result.json()
} catch (err) {
console.log(err)
return null
}
}
const FunctionalComponent = () => {
const [userData, setUserData] = useState()
useEffect(() => {
fetchUserData().then(data => {
data && setUserData(data)
})
}, []) // componentDidMount
return <div />
}
Ben Awad's awesome tutorial
Example:
it seems that you are making it more complicated than it should be. When you get the response i.e the resolved promise with the data inside the async function, just set the state and in the next render you should get the updated data.
Example:
const [userData, setUserData] = useState();
useEffect(() => {
const getResponse = async () => {
try {
const result = await fetch(`/usermanagement/getdocent`, {
method: "GET"
});
const body = await result.json();
setUserData(body);
} catch (err) {
console.log(err)
}
}
getResponse();
}, [])
console.log(userData);
return <div></div>
Assuming the you need to call the function only once define and call it inside a useEffect or 'componentDidMount'. For using async function inside useEffect we need to define another function and then call it.
When you do
let userTestData
// This line does not wait and next line is executed immediately before userTestData is set
fetchUserData().then(data => {userTestData = data});
console.log(userTestData);
// Try changing to
async someAsyncScope() {
const userTestData = await fetchUserData();
console.log(userTestData)
}
Example:
state = {
someKey: 'someInitialValue'
};
async myAsyncMethod() {
const myAsyncValue = await anotherAsyncMethod();
this.setState({ someKey: myAsyncValue });
}
/*
* Then in the template or where ever, use a state variable which you update when
* the promise resolves. When a state value is used, once the state is updated,
* it triggers as a re-render
*/
render() {
return <div>{this.state.someKey}</div>;
}
In your example you'd use setUserData instead of this.setState and userData instead of {this.state.someKey}
I have a custom hook that I'm using to make API requests on my react front-end application but the hook seems to be having a bug.
It makes API requests as intended but whenever I unmount the current container/page in which the request is being made, my hook doesn't know that the page has been unmounted so it doesn't cancel the request and therefore react throws the 'Can't perform a React state update on an unmounted component' warning.
export function useFetch(initialValue, url, options, key) {
const [response, setResponse] = useLocalStorage(key, initialValue);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const isMounted = { state: true };
async function fetchData() {
setLoading(true);
try {
const res = await axios({
url: url,
baseURL: BASE_URL,
cancelToken: source.token,
...options
});
if (res.data.results) {
setResponse(res.data.results);
} else {
setResponse(res.data);
}
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
}
if (isMounted.state) {
fetchData();
}
return () => {
isMounted.state = false;
source.cancel('Operation canceled by the user.');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url]);
return [response, { error, loading }];
}
By now you are checking for if(isMounter.state) in wrong place. It's currently very next step after you've initialized it.
I believe it should be
const isMounted = { state: true };
async function fetchData() {
setLoading(true);
try {
const res = await axios({
url: url,
baseURL: BASE_URL,
cancelToken: source.token,
...options
});
if(!isMounted.state) return;
.....
}
}
fetchData();
BTW you don't have to use object there: isMounted = true/isMounted = false will work just fine through closure.
Actually your have 2 different approaches mixed: using flag(isMounted) and cancelling request. You may use just one. Cancelling request should work(as far as I see) but it leads your catch block is executed:
} catch (error) {
setError(error);
setLoading(false);
}
See, unmounting cancels request, but your code still tries to set up some state. Probably you better check if request has been failed or canceled with axious.isCancel:
} catch (error) {
if (!axios.isCancel(error)) {
setError(error);
setLoading(false);
}
}
And you may get rid of isMounted in this case.
I use the following hook to get an ifMounted function
const useIfMounted = () => {
const isMounted = useRef(true)
useEffect(
() => () => {
isMounted.current = false
},[]
)
const ifMounted = useCallback(
func => {
if (isMounted.current && func) {
func()
}
},[]
)
return ifMounted
}
Then in your code add const ifMounted = useIfMounted() to useFetch and before your set functions do ifMounted(() => setLoading(true), ifMounted(() => setError(error)), etc....
Here's a blog post I wrote on the subject: https://aceluby.github.io/blog/react-hooks-cant-set-state-on-an-unmounted-component
I'm trying to write a custom fetch hook, but I guess im missing something.
import React, { useContext } from 'react';
import { Context } from "../components/context";
const fetchHook = async(url: string, bearer: string, method: string, body: any ) => {
const { global } = useContext(Context) as {global: any};
let headers = {'cache-control': 'no-cache', 'Content-Type': 'application/json' };
if (bearer) headers = {...headers, ...{'Authorization': bearer}}
if (method === 'GET') return await fetch(global.apiUrl + url, {method, headers});
else return await fetch(global.apiUrl + url, {method, headers, body});
}
export { fetchHook }
The error im getting is Line 5: React Hook "useContext" is called in function "fetchHook" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
UPDATE:
import React, { useContext } from 'react';
import { Context } from "../components/context";
const useFetch = (url: string, bearer: string, method: string, body: any) => {
const { global } = useContext(Context) as {global: any};
let headers = {'cache-control': 'no-cache', 'Content-Type': 'application/json' };
if (bearer) headers = {...headers, ...{'Authorization': bearer}}
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const apiUrl = global.apiUrl;
React.useEffect(() => {
const fetchData = async () => {
try {
let res;
if (method === 'GET') res = await fetch(apiUrl + url, {method, headers});
else res = await fetch(global.apiUrl + url, {method, headers, body});
setResponse(await res.json());
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};
export { useFetch }
The only warning I get now I about a missing dependency warning but I'm not sure how to fix it. Should I be passing all the dependencies into the square brackets of useEffect()?? I'm just not sure?
Line 27: React Hook React.useEffect has missing dependencies: 'apiUrl', 'body', 'global.apiUrl', 'headers', 'method', and 'url'. Either include them or remove the dependency array
You are getting this warning because according to the Rules of hooks, a custom hook name must start with use.
As mentioned the docs of custom hooks
A custom Hook is a JavaScript function whose name starts with ”use”
and that may call other Hooks.
You won't receive the error if you rename the hook to
const useFetchHook = async(url: string, bearer: string, method: string, body: any ) => {
const { global } = useContext(Context) as {global: any};
let headers = {'cache-control': 'no-cache', 'Content-Type': 'application/json' };
if (bearer) headers = {...headers, ...{'Authorization': bearer}}
if (method === 'GET') return await fetch(global.apiUrl + url, {method, headers});
else return await fetch(global.apiUrl + url, {method, headers, body});
}
export { useFetchHook }
Also one thing you must keep in mind is that if you execute async code within the custom hook directly, it will be executed on every render. A better way is to maintain state and fetch the data within useEffect and update the state when the data is received.
In order to get data from my AWS Postgres DB, I have to first get an AWS Access Token and pass it into the GET call. To accomplish this, in my React app, I've created a file called requests.js into which I plan to build a number of functions. Here are the first two:
// Custom hook to get AWS Auth Token
export const useGetAwsAuthToken = () => {
const [data, setData] = useState();
useEffect(() => {
const fetchData = async function() {
try {
const config = {
headers: { "Authorization":
await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
})
}
};
setData(config);
} catch (error) {
throw error;
} finally {
}
};
fetchData();
}, []);
return { data };
};
// Custom hook for performing GET requests
export const useFetch = (url, initialValue) => {
const [data, setData] = useState(initialValue);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async function() {
try {
setLoading(true);
const response = await axios.get(url);
if (response.status === 200) {
setData(response.data);
}
} catch (error) {
throw error;
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { loading, data };
};
I was under the impression that I could use const [data, setData] = useState(); in both of these functions and that they would be independent of each other. However, back where I call the functions, my IDE is telling me that "data has already been declared" with the 2nd call:
const {data} = useGetAwsAuthToken();
const {loading, data} = useFetch('https://jsonplaceholder.typicode.com/posts');
Furthermore, say I comment out the 2nd line of code above and make this call:
const {data2} = useGetAwsAuthToken();
This leaves data2 as undefined. This is also confusing because shouldn't I be able to have any named return value variable in the calling function?
First, the one that is easier to answer for me: const {data2} = useGetAwsAuthToken isn't valid because you're using destructuring and it's expecting the value of data. So what you're telling it is the equivalent of saying const data2 = useGetAwsAuthToken().data2 What you actually want is const { data: data2 } = useGetAwsAuthToken(). This will take the value that is returned (data) and save it to the current scope as data2.
Now for the first issue you brought up. Why are you using react life cycles in what appears to just be a function? You don't need to save things in state when it's just a function that's not returning a React Component.