Custom useAxios hook in react - reactjs

I am using axios with react, so I thought to write a custom hook for this which I did and it is working fine like below
const useAxios = () => {
const [response, setResponse] = useState([]);
const [error, setError] = useState("");
const [loading, setLoading] = useState(true); //different!
const [controller, setController] = useState();
const axiosFetch = async (configObj) => {
const { axiosInstance, method, url, requestConfig = {} } = configObj;
try {
const ctrl = new AbortController();
setController(ctrl);
const res = await axiosInstance[method.toLowerCase()](url, {
...requestConfig,
});
setResponse(res.data);
} catch (err) {
console.log(err.message);
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
console.log(controller);
// useEffect cleanup function
return () => controller && controller.abort();
}, [controller]);
return [response, error, loading, axiosFetch];
};
I have also created one axiosInstance to pass BASE_URL and headers.
Now calling useAxios to fetch data from api like below
const [data, error, loading, axiosFetch] = useAxios();
const getData = () => {
axiosFetch({
axiosInstance: axios,
method: "GET",
url: "/url",
});
};
useEffect(() => {
getData();
}, []);
My Question is
When I need to call one api I am doing above.
But what if I have to call three or four APIs in a single page.
Shall I replicate the code like this const [data1, error1, loading1, axiosFetch]=useAxios();
Or is there any other way to minimize the code.
Edit / Update
I ran above code to get data from /url, what if I want to hit different route to get one more data from server for other work, the base url remains the same
So if the second route is /users
const [data, error, loading, axiosFetch] = useAxios();
const getUsers = () => {
axiosFetch({
axiosInstance: axios,
method: "GET",
url: "/users",
});
};
useEffect(() => {
getUsers();
}, [on_BTN_Click]);
THe above codeI want to run in same file, one to get data and one to get users, how should I write my axios, as I think this const [data, error, loading, axiosFetch] = useAxios(); should gets called only once, Don't know how to do this or what is the correct way, shall I need to change my useAxios hook?

What you could do is pass the endpoint to the hook or properly call the axiosFetch callback with the different endpoints. But I have another opinion about what you are trying to do and here are my 5 cents on why this "axios hook" might not be a good idea.
A good rule of thumb on React Hooks is to use a custom hook if you need to encapsulate component logic that uses React Hooks.
Another important thing that is described in the React Hooks docs is:
Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.
So, eventually, if 2 different components call the fetch for the same endpoint, they both are going to execute the call to the Backend. How to prevent that? Well, you could use a lib such as React Query, that creates some kind of "cache" for you (and a bunch of other nice features!)
And last but not least: API calls are much more related to a Service/Module than a React Hook (isolate component logic), as a concept. I hardly advise you to create a service for making API calls and using that service inside your hook instead of coupling that logic to your hook and having to handle all kinds of issues such as Caching and multiple instances of the same hook or even multiple instances of this hook calling multiple different endpoints that eventually could or could not be dependant of themselves.

How about a generic useAsync hook that accepts any asynchronous call? This decouples axios specifics from the the hook.
function useAsync(func, deps = []) {
const [state, setState] = useState({ loading: true, error: null, data: null })
useEffect(
() => {
let mounted = true
func()
.then(data => mounted && setState({ loading: false, error: null, data }))
.catch(error => mounted && setState({ loading: false, error, data: null }))
return () => { mounted = false }
},
deps,
)
return state
}
Here's a basic example of its usage -
function UserProfile({ userId }) {
const user = useAsync(
() => axios.get(`/users/${userId}`), // async call
[userId], // dependencies
})
if (user.loading)
return <Loading />
if (user.error)
return <Error message={user.error.message} />
return <User user={user.data} />
}
The idea is any asynchronous operation can be performed. A more sophisticated example might look like this -
function UserProfile({ userId }) {
const profile = useAsync(
async () => {
const user = await axios.get(`/users/${userId}`)
const friends = await axios.get(`/users/${userId}/friends`)
const notifications = await axios.get(`/users/${userId}/notifications`)
return {user, friends, notifications}
},
[userId],
)
if (profile.loading) return <Loading />
if (profile.error) return <Error message={profile.error.message} />
return <>
<User user={profile.data.user} />
<Friends friends={profile.data.friends} />
<Notifications notifications={profile.data.notifications} />
</>
}
In the last example, all fetches need to complete before the data can begin rendering. You could use the useAsync hook multiple times to get parallel processing. Don't forget you have to check for loading and error before you can safely access data -
function UserProfile({ userId }) {
const user = useAsync(() => axios.get(`/users/${userId}`), [userId])
const friends = useAsync(() => axios.get(`/users/${userId}/friends`), [userId])
const notifications = useAsync(() => axios.get(`/users/${userId}/notifications`), [userId])
return <>
{ user.loading
? <Loading />
: user.error
? <Error message={user.error.message }
: <User user={user.data} />
}
{ friends.loading
? <Loading />
: friends.error
? <Error message={friends.error.message} />
: <Friends friends={friends.data} />
}
{ notifications.loading
? <Loading />
: notifications.error
? <Error message={notifications.error.message} />
: <Notifications notifications={notifications.data} />
}
</>
}
I would recommend you decouple axios from your components as well. You can do this by writing your own API module and even providing a useAPI hook. See this Q&A if that sounds interesting to you.

Related

Rendering different elements based on promise's result

I'm trying to make a login/logout button based on my user authentication status. since I'm fetching this data from my api, I cant seem to return the data itself, only the promise and since in reactjs the .then() function cant be used I don't know how to access the data I need.
this is the function that fetches the data from api, I want it to return "data.success" which is a boolean, but instead a promise is returned.
let checkAuth = () => {
return fetch('/v1/checkLogin')
.then(response => response.json())
.then(data => {
return data.success
})
}
react code calling above function :
{
(checkAuth())
? <button>logout</button>
: <button>login</button>
}
any help is appreciated =)
Due to the asynchronous nature of requests, the outer code will have already returned before the promise is resolved. That is why it returns a promise instead of your data.
A better approach to get through this is to use "useState" "useEffect" hooks
use "useEffect" to fetch the data when the component renders for the first time
use "useState" store the fetched data to a variable and use it in ways you want
export default LoginComponent = () => {
const [authenticated, setAuthenticated] = useState(false); // False initially
let checkAuth = () => {
const result = await fetch("/v1/checkLogin") // Wait for promise to resolve
const data = result.json();
setAuthenticated(data.success); // Set Data. (You can set just "data" if you want the whole data object)
};
// useEffect which fires once when the component initially renders
useEffect(() => {
checkAuth()
}, []);
return (
<div>
{authenticated ? <button>logout</button> : <button>login</button
</div>
);
};
You can use a state with useEffect to update the UI accordingly
const YourComponent = () => {
const [isAccess, setIsAccess] = useState(); // initialize your state
let checkAuth = () => {
return fetch("/v1/checkLogin")
.then((response) => response.json())
.then((data) => {
setIsAccess(data.success); //set the value for your state
});
};
useEffect(() => {
checkAuth()
}, [])
//after the state update, your UI will be re-rendered with the latest value which you expected
return (
<div>{isAccess ? <button>logout</button> : <button>login</button>}</div>
);
};

useEffect: Can't perform a React state update on an unmounted component [duplicate]

When fetching data I'm getting: Can't perform a React state update on an unmounted component. The app still works, but react is suggesting I might be causing a memory leak.
This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."
Why do I keep getting this warning?
I tried researching these solutions:
https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
https://developer.mozilla.org/en-US/docs/Web/API/AbortController
but this still was giving me the warning.
const ArtistProfile = props => {
const [artistData, setArtistData] = useState(null)
const token = props.spotifyAPI.user_token
const fetchData = () => {
const id = window.location.pathname.split("/").pop()
console.log(id)
props.spotifyAPI.getArtistProfile(id, ["album"], "US", 10)
.then(data => {setArtistData(data)})
}
useEffect(() => {
fetchData()
return () => { props.spotifyAPI.cancelRequest() }
}, [])
return (
<ArtistProfileContainer>
<AlbumContainer>
{artistData ? artistData.artistAlbums.items.map(album => {
return (
<AlbumTag
image={album.images[0].url}
name={album.name}
artists={album.artists}
key={album.id}
/>
)
})
: null}
</AlbumContainer>
</ArtistProfileContainer>
)
}
Edit:
In my api file I added an AbortController() and used a signal so I can cancel a request.
export function spotifyAPI() {
const controller = new AbortController()
const signal = controller.signal
// code ...
this.getArtist = (id) => {
return (
fetch(
`https://api.spotify.com/v1/artists/${id}`, {
headers: {"Authorization": "Bearer " + this.user_token}
}, {signal})
.then(response => {
return checkServerStat(response.status, response.json())
})
)
}
// code ...
// this is my cancel method
this.cancelRequest = () => controller.abort()
}
My spotify.getArtistProfile() looks like this
this.getArtistProfile = (id,includeGroups,market,limit,offset) => {
return Promise.all([
this.getArtist(id),
this.getArtistAlbums(id,includeGroups,market,limit,offset),
this.getArtistTopTracks(id,market)
])
.then(response => {
return ({
artist: response[0],
artistAlbums: response[1],
artistTopTracks: response[2]
})
})
}
but because my signal is used for individual api calls that are resolved in a Promise.all I can't abort() that promise so I will always be setting the state.
For me, clean the state in the unmount of the component helped.
const [state, setState] = useState({});
useEffect(() => {
myFunction();
return () => {
setState({}); // This worked for me
};
}, []);
const myFunction = () => {
setState({
name: 'Jhon',
surname: 'Doe',
})
}
Sharing the AbortController between the fetch() requests is the right approach.
When any of the Promises are aborted, Promise.all() will reject with AbortError:
function Component(props) {
const [fetched, setFetched] = React.useState(false);
React.useEffect(() => {
const ac = new AbortController();
Promise.all([
fetch('http://placekitten.com/1000/1000', {signal: ac.signal}),
fetch('http://placekitten.com/2000/2000', {signal: ac.signal})
]).then(() => setFetched(true))
.catch(ex => console.error(ex));
return () => ac.abort(); // Abort both fetches on unmount
}, []);
return fetched;
}
const main = document.querySelector('main');
ReactDOM.render(React.createElement(Component), main);
setTimeout(() => ReactDOM.unmountComponentAtNode(main), 1); // Unmount after 1ms
<script src="//cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.development.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.development.js"></script>
<main></main>
For example, you have some component that does some asynchronous actions, then writes the result to state and displays the state content on a page:
export default function MyComponent() {
const [loading, setLoading] = useState(false);
const [someData, setSomeData] = useState({});
// ...
useEffect( () => {
(async () => {
setLoading(true);
someResponse = await doVeryLongRequest(); // it takes some time
// When request is finished:
setSomeData(someResponse.data); // (1) write data to state
setLoading(false); // (2) write some value to state
})();
}, []);
return (
<div className={loading ? "loading" : ""}>
{someData}
<Link to="SOME_LOCAL_LINK">Go away from here!</Link>
</div>
);
}
Let's say that user clicks some link when doVeryLongRequest() still executes. MyComponent is unmounted but the request is still alive and when it gets a response it tries to set state in lines (1) and (2) and tries to change the appropriate nodes in HTML. We'll get an error from subject.
We can fix it by checking whether compponent is still mounted or not. Let's create a componentMounted ref (line (3) below) and set it true. When component is unmounted we'll set it to false (line (4) below). And let's check the componentMounted variable every time we try to set state (line (5) below).
The code with fixes:
export default function MyComponent() {
const [loading, setLoading] = useState(false);
const [someData, setSomeData] = useState({});
const componentMounted = useRef(true); // (3) component is mounted
// ...
useEffect( () => {
(async () => {
setLoading(true);
someResponse = await doVeryLongRequest(); // it takes some time
// When request is finished:
if (componentMounted.current){ // (5) is component still mounted?
setSomeData(someResponse.data); // (1) write data to state
setLoading(false); // (2) write some value to state
}
return () => { // This code runs when component is unmounted
componentMounted.current = false; // (4) set it to false when we leave the page
}
})();
}, []);
return (
<div className={loading ? "loading" : ""}>
{someData}
<Link to="SOME_LOCAL_LINK">Go away from here!</Link>
</div>
);
}
Why do I keep getting this warning?
The intention of this warning is to help you prevent memory leaks in your application. If the component updates it's state after it has been unmounted from the DOM, this is an indication that there could be a memory leak, but it is an indication with a lot of false positives.
How do I know if I have a memory leak?
You have a memory leak if an object that lives longer than your component holds a reference to it, either directly or indirectly. This usually happens when you subscribe to events or changes of some kind without unsubscribing when your component unmounts from the DOM.
It typically looks like this:
useEffect(() => {
function handleChange() {
setState(store.getState())
}
// "store" lives longer than the component,
// and will hold a reference to the handleChange function.
// Preventing the component to be garbage collected after
// unmount.
store.subscribe(handleChange)
// Uncomment the line below to avoid memory leak in your component
// return () => store.unsubscribe(handleChange)
}, [])
Where store is an object that lives further up the React tree (possibly in a context provider), or in global/module scope. Another example is subscribing to events:
useEffect(() => {
function handleScroll() {
setState(window.scrollY)
}
// document is an object in global scope, and will hold a reference
// to the handleScroll function, preventing garbage collection
document.addEventListener('scroll', handleScroll)
// Uncomment the line below to avoid memory leak in your component
// return () => document.removeEventListener(handleScroll)
}, [])
Another example worth remembering is the web API setInterval, which can also cause memory leak if you forget to call clearInterval when unmounting.
But that is not what I am doing, why should I care about this warning?
React's strategy to warn whenever state updates happen after your component has unmounted creates a lot of false positives. The most common I've seen is by setting state after an asynchronous network request:
async function handleSubmit() {
setPending(true)
await post('/someapi') // component might unmount while we're waiting
setPending(false)
}
You could technically argue that this also is a memory leak, since the component isn't released immediately after it is no longer needed. If your "post" takes a long time to complete, then it will take a long time to for the memory to be released. However, this is not something you should worry about, because it will be garbage collected eventually. In these cases, you could simply ignore the warning.
But it is so annoying to see the warning, how do I remove it?
There are a lot of blogs and answers on stackoverflow suggesting to keep track of the mounted state of your component and wrap your state updates in an if-statement:
let isMountedRef = useRef(false)
useEffect(() => {
isMountedRef.current = true
return () => {
isMountedRef.current = false
}
}, [])
async function handleSubmit() {
setPending(true)
await post('/someapi')
if (!isMountedRef.current) {
setPending(false)
}
}
This is not an recommended approach! Not only does it make the code less readable and adds runtime overhead, but it might also might not work well with future features of React. It also does nothing at all about the "memory leak", the component will still live just as long as without that extra code.
The recommended way to deal with this is to either cancel the asynchronous function (with for instance the AbortController API), or to ignore it.
In fact, React dev team recognises the fact that avoiding false positives is too difficult, and has removed the warning in v18 of React.
You can try this set a state like this and check if your component mounted or not. This way you are sure that if your component is unmounted you are not trying to fetch something.
const [didMount, setDidMount] = useState(false);
useEffect(() => {
setDidMount(true);
return () => setDidMount(false);
}, [])
if(!didMount) {
return null;
}
return (
<ArtistProfileContainer>
<AlbumContainer>
{artistData ? artistData.artistAlbums.items.map(album => {
return (
<AlbumTag
image={album.images[0].url}
name={album.name}
artists={album.artists}
key={album.id}
/>
)
})
: null}
</AlbumContainer>
</ArtistProfileContainer>
)
Hope this will help you.
I had a similar issue with a scroll to top and #CalosVallejo answer solved it :) Thank you so much!!
const ScrollToTop = () => {
const [showScroll, setShowScroll] = useState();
//------------------ solution
useEffect(() => {
checkScrollTop();
return () => {
setShowScroll({}); // This worked for me
};
}, []);
//----------------- solution
const checkScrollTop = () => {
setShowScroll(true);
};
const scrollTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" });
};
window.addEventListener("scroll", checkScrollTop);
return (
<React.Fragment>
<div className="back-to-top">
<h1
className="scrollTop"
onClick={scrollTop}
style={{ display: showScroll }}
>
{" "}
Back to top <span>⟶ </span>
</h1>
</div>
</React.Fragment>
);
};
I have getting same warning, This solution Worked for me ->
useEffect(() => {
const unsubscribe = fetchData(); //subscribe
return unsubscribe; //unsubscribe
}, []);
if you have more then one fetch function then
const getData = () => {
fetch1();
fetch2();
fetch3();
}
useEffect(() => {
const unsubscribe = getData(); //subscribe
return unsubscribe; //unsubscribe
}, []);
This error occurs when u perform state update on current component after navigating to other component:
for example
axios
.post(API.BASE_URI + API.LOGIN, { email: username, password: password })
.then((res) => {
if (res.status === 200) {
dispatch(login(res.data.data)); // line#5 logging user in
setSigningIn(false); // line#6 updating some state
} else {
setSigningIn(false);
ToastAndroid.show(
"Email or Password is not correct!",
ToastAndroid.LONG
);
}
})
In above case on line#5 I'm dispatching login action which in return navigates user to the dashboard and hence login screen now gets unmounted.
Now when React Native reaches as line#6 and see there is state being updated, it yells out loud that how do I do this, the login component is there no more.
Solution:
axios
.post(API.BASE_URI + API.LOGIN, { email: username, password: password })
.then((res) => {
if (res.status === 200) {
setSigningIn(false); // line#6 updating some state -- moved this line up
dispatch(login(res.data.data)); // line#5 logging user in
} else {
setSigningIn(false);
ToastAndroid.show(
"Email or Password is not correct!",
ToastAndroid.LONG
);
}
})
Just move react state update above, move line 6 up the line 5.
Now state is being updated before navigating the user away. WIN WIN
there are many answers but I thought I could demonstrate more simply how the abort works (at least how it fixed the issue for me):
useEffect(() => {
// get abortion variables
let abortController = new AbortController();
let aborted = abortController.signal.aborted; // true || false
async function fetchResults() {
let response = await fetch(`[WEBSITE LINK]`);
let data = await response.json();
aborted = abortController.signal.aborted; // before 'if' statement check again if aborted
if (aborted === false) {
// All your 'set states' inside this kind of 'if' statement
setState(data);
}
}
fetchResults();
return () => {
abortController.abort();
};
}, [])
Other Methods:
https://medium.com/wesionary-team/how-to-fix-memory-leak-issue-in-react-js-using-hook-a5ecbf9becf8
If the user navigates away, or something else causes the component to get destroyed before the async call comes back and tries to setState on it, it will cause the error. It's generally harmless if it is, indeed, a late-finish async call. There's a couple of ways to silence the error.
If you're implementing a hook like useAsync you can declare your useStates with let instead of const, and, in the destructor returned by useEffect, set the setState function(s) to a no-op function.
export function useAsync<T, F extends IUseAsyncGettor<T>>(gettor: F, ...rest: Parameters<F>): IUseAsync<T> {
let [parameters, setParameters] = useState(rest);
if (parameters !== rest && parameters.some((_, i) => parameters[i] !== rest[i]))
setParameters(rest);
const refresh: () => void = useCallback(() => {
const promise: Promise<T | void> = gettor
.apply(null, parameters)
.then(value => setTuple([value, { isLoading: false, promise, refresh, error: undefined }]))
.catch(error => setTuple([undefined, { isLoading: false, promise, refresh, error }]));
setTuple([undefined, { isLoading: true, promise, refresh, error: undefined }]);
return promise;
}, [gettor, parameters]);
useEffect(() => {
refresh();
// and for when async finishes after user navs away //////////
return () => { setTuple = setParameters = (() => undefined) }
}, [refresh]);
let [tuple, setTuple] = useState<IUseAsync<T>>([undefined, { isLoading: true, refresh, promise: Promise.resolve() }]);
return tuple;
}
That won't work well in a component, though. There, you can wrap useState in a function which tracks mounted/unmounted, and wraps the returned setState function with the if-check.
export const MyComponent = () => {
const [numPendingPromises, setNumPendingPromises] = useUnlessUnmounted(useState(0));
// ..etc.
// imported from elsewhere ////
export function useUnlessUnmounted<T>(useStateTuple: [val: T, setVal: Dispatch<SetStateAction<T>>]): [T, Dispatch<SetStateAction<T>>] {
const [val, setVal] = useStateTuple;
const [isMounted, setIsMounted] = useState(true);
useEffect(() => () => setIsMounted(false), []);
return [val, newVal => (isMounted ? setVal(newVal) : () => void 0)];
}
You could then create a useStateAsync hook to streamline a bit.
export function useStateAsync<T>(initialState: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
return useUnlessUnmounted(useState(initialState));
}
Try to add the dependencies in useEffect:
useEffect(() => {
fetchData()
return () => { props.spotifyAPI.cancelRequest() }
}, [fetchData, props.spotifyAPI])
Usually this problem occurs when you showing the component conditionally, for example:
showModal && <Modal onClose={toggleModal}/>
You can try to do some little tricks in the Modal onClose function, like
setTimeout(onClose, 0)
This works for me :')
const [state, setState] = useState({});
useEffect( async ()=>{
let data= await props.data; // data from API too
setState(users);
},[props.data]);
I had this problem in React Native iOS and fixed it by moving my setState call into a catch. See below:
Bad code (caused the error):
const signupHandler = async (email, password) => {
setLoading(true)
try {
const token = await createUser(email, password)
authContext.authenticate(token)
} catch (error) {
Alert.alert('Error', 'Could not create user.')
}
setLoading(false) // this line was OUTSIDE the catch call and triggered an error!
}
Good code (no error):
const signupHandler = async (email, password) => {
setLoading(true)
try {
const token = await createUser(email, password)
authContext.authenticate(token)
} catch (error) {
Alert.alert('Error', 'Could not create user.')
setLoading(false) // moving this line INTO the catch call resolved the error!
}
}
Similar problem with my app, I use a useEffect to fetch some data, and then update a state with that:
useEffect(() => {
const fetchUser = async() => {
const {
data: {
queryUser
},
} = await authFetch.get(`/auth/getUser?userId=${createdBy}`);
setBlogUser(queryUser);
};
fetchUser();
return () => {
setBlogUser(null);
};
}, [_id]);
This improves upon Carlos Vallejo's answer.
useEffect(() => {
let abortController = new AbortController();
// your async action is here
return () => {
abortController.abort();
}
}, []);
in the above code, I've used AbortController to unsubscribe the effect. When the a sync action is completed, then I abort the controller and unsubscribe the effect.
it work for me ....
The easy way
let fetchingFunction= async()=>{
// fetching
}
React.useEffect(() => {
fetchingFunction();
return () => {
fetchingFunction= null
}
}, [])
options={{
filterType: "checkbox"
,
textLabels: {
body: {
noMatch: isLoading ?
:
'Sorry, there is no matching data to display',
},
},
}}

React custom fetch hook is one step behind

I am creating my custom fetch hook for both get and post data. I was following official React docs for creating custom fetch hooks, but it looks like my hook-returned state variables are one step behind behind due to useState asynchronous behaviour. Here is my custom useMutation hook
export const useMutationAwait = (url, options) => {
const [body, setBody] = React.useState({});
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);
React.useEffect(() => {
const fetchData = async () => {
setError(null);
setIsLoading(true);
console.log("...fetching");
try {
const response = await axiosInstance.post(url, body, options);
setData(response.status);
} catch (error) {
console.error(error.response.data);
setError(error.response.data);
}
setIsLoading(false);
};
fetchData();
}, [body]);
return [{ data, isLoading, error }, setBody];
};
And I am using it in my component like this (simplified) - when user presses register button I want to be able immediately decide if my post was successful or not and according to that either navigate user to another screen or display fetch error.
const [email, setEmail] = React.useState('');
const [password, setPassword] React.useState('');
const [{ data: mutData, error: mutError }, sendPost] =
useMutationAwait("/auth/pre-signup");
const registerUser = async () => {
sendPost({
email,
password,
}); ---> here I want to evaluate the result but when I log data and error, the results come after second log (at first they are both null as initialised in hook)
Is this even correct approach that I am trying to achieve? Basically I want to create some generic function for data fetching and for data mutating and I thought hooks could be the way.
Your approach isn't wrong, but the code you're sharing seams to be incomplete or maybe outdated? Calling sendPost just update some state inside your custom hook but assuming calling it will return a promise (your POST request) you should simply use async-await and wrap it with a try-catch statement.
export const useMutationAwait = (url, options) => {
const sendPost = async (body) => {
// submit logic here & return request promise
}
}
const registerUser = async () => {
try {
const result = await sendPost({ login, password });
// do something on success
} catch (err) {
// error handling
}
}
Some recommendations, since you're implementing your custom hook, you could implement one that only fetch fetch data and another that only submit requests (POST). Doing this you have more liberty since some pages will only have GET while others will have POST or PUT. Basically when implementing a hook try making it very specific to one solution.
You're absolutely correct for mentioning the asynchronous nature of state updates, as that is the root of the problem you're facing.
What is happening is as follows:
You are updating the state by using sendPost inside of a function.
React state updates are function scoped. This means that React runs all setState() calls it finds in a particular function only after the function is finished running.
A quote from this question:
React batches state updates that occur in event handlers and lifecycle methods. Thus, if you update state multiple times in a handler, React will wait for event handling to finish before re-rendering.
So setBody() in your example is running after you try to handle the response, which is why it is one step behind.
Solution
In the hook, I would create handlers which have access to the data and error variables. They take a callback (like useEffect does) and calls it with the variable only if it is fresh. Once it is done handling, it sets it back to null.
export const useMutationAwait = (url, options) => {
const [body, setBody] = React.useState({});
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);
const handleData = (callback) => {
if (data){
callback(data);
setData(null);
}
}
const handleError = (callback) => {
if (error){
callback(error);
setError(null);
}
}
React.useEffect(() => {
const fetchData = async () => {
setError(null);
setIsLoading(true);
console.log("...fetching");
try {
const response = await axiosInstance.post(url, body, options);
setData(response.status);
} catch (error) {
console.error(error.response.data);
setError(error.response.data);
}
setIsLoading(false);
};
fetchData();
}, [body]);
return [{ data, handleData, isLoading, error, handleError }, setBody];
};
We now register the handlers when the component is rendered, and everytime data or error changes:
const [
{
data: mutData,
handleData: handleMutData,
error: mutError,
handleError: handleMutError
}, sendPost] = useMutationAwait("/auth/pre-signup");
handleMutData((data) => {
// If you get here, data is fresh.
});
handleMutError((error) => {
// If you get here, error is fresh.
});
const registerUser = async () => {
sendPost({
email,
password,
});
Just as before, every time the data changes the component which called the hook will also update. But now, every time it updates it calls the handleData or handleError function which in turn runs our custom handler with the new fresh data.
I hope this helped, let me know if you're still having issues.

React Hooks : Conditionally call another custom hook

I have a an async hook, which gets the user useGetUser
function useGetUser() {
const [user, setUser] = useState(false);
useEffect(() => {
async function getUser() {
const session = await Auth.currentSession();
setUser(session);
}
if (!user) {
getUser();
}
}, [user]);
return user;
}
From another hook, I'm calling this hook, and only when I get the user, I want to execute the query:
function useGraphQLQuery() {
const user = useGetUser();
useEffect(() => {
if (user) {
useQuery(`blablabla`, async () =>
request(endpoint, query, undefined, {
authorization: user.getAccessToken().getJwtToken() || '',
})
);
}
}, [user]);
}
This code doesn't work because useQuery needs to be outside of useEffect and also because of the condition, but I need to wait for the user to be fetched...
Thank you.
I think you should have a slightly different approach.
For example , encapsulate all your routes into a component , let's call it App , in App.js. In App.js you want to use the useEffect hook to check if the user is authentificated or not, something like this:
React.useEffect(() => {
//We refresh the access token every time the page is changed
fetch('http://localhost:1000/refresh_token', {
method: 'POST',
credentials: 'include',
}).then(async x => {
const { accessToken } = await x.json()
// we set the access token
setAccessToken(accessToken)
setLoading(false)
})
}, [])
Then , from the App component, render all your components , just like in index.js.
Now you can easily use the useQuery hook in each of your components corresponding to a page .
The useGetUser hook is a bit strange since it uses a state variable which also is being set by the effect. Since it is really easy to get unwanted effects or even infinite render loops, I would prevent that.
Since it only needs to run once on startup, you can remove the !user part and also the user dependency. I can imagine you would like this hook to be updated when the Auth service receives a session.
function useGetUser() {
const [user, setUser] = useState(false);
useEffect(() => {
async function getUser() {
const session = await Auth.currentSession();
setUser(session);
}
getUser();
}, []);
return user;
}
For the useQuery hook, you can use the enabled option to prevent the useQuery from executing when set to false. You can also remove the useEffect since it's already a hook which responds to option changes.
function useGraphQLQuery() {
const user = useGetUser();
useQuery(`blablabla`, async () => request(endpoint, query, undefined, {
authorization: user.getAccessToken().getJwtToken() || '',
}), { enabled: !!user });
}

Conditionally calling an API using React-Query hook

I am using react-query to make API calls, and in this problem case I want to only call the API if certain conditions are met.
I have an input box where users enter a search query. When the input value is changed, a search server is called with the contents of the input as the search query ... but only if the input value is more than 3 chars long.
In my react component I'm calling:
const {data, isLoading} = useQuery(['search', searchString], getSearchResults);
And my getSearchResults function will, conditionally, make an API call.
const getSearchResults = async (_, searchString) => {
if (searchString.length < 3)
return {data: []}
const {data} = await axios.get(`/search?q=${searchString}`)
return data;
}
We can't use a hook inside a conditional - so I put the condition into my API calling function.
This almost works. If I enter a short query string, there is no API request made and I get an empty array back for the data. Yay!
But - isLoading will flip to true briefly - even though there is no HTTP request being made. So my loading indicator shows when there is no actual network activity.
Am I misunderstanding how to best solve my use case, is there a way to enure that isLoading will return false if there is no HTTP activity?
The key was to use Dependent Queries
So, in my main component, I create a boolean and pass that to the enabled option of the useQuery hook:
const isLongEnough = searchString.length > 3;
const {data, isLoading} = useQuery(['search', searchString], getSearchResults, {enabled: isLongEnough});
and the API calling method is simply the API call - not any conditional:
const getSearchResults = async (_, searchString) => {
const {data} = await axios.get(`/search?q=${searchString}`);
return data;
}
The docs describe dependent queries as a solution for loading data from subsequent API endpoints, but the enable option can accept any boolean. In this case - if the search query string is long enough.
There's another option which is to use queryClient.fetchQuery API, which gives you the ability to conditionally call the query to fetch the data.
function Example2() {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
if (isLoading) return "Loading...";
if (error) return "An error has occurred: " + error;
return (
<div>
<button
onClick={async () => {
try {
setIsLoading(true);
const posts = await queryClient.fetchQuery(
["postsUsingFetchQuery"],
{
queryFn: () =>
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.data)
}
);
setData(posts);
} catch (e) {
setError(e);
}
setIsLoading(false);
}}
>
Fetch posts using fetchQuery{" "}
</button>
<h1>Posts</h1>
{data?.map((post) => {
return (
<div style={{ display: "flex" }}>
<span>{post.id}- </span>
<div>{post.title}</div>
</div>
);
})}
</div>
);
}
On the button click handler, we’ve added the implementation to fetch the posts using queryClient.fetchQuery.
You can read more from this link.

Resources