Axios cancelToken in useEffect cleanup - reactjs

I would like to implement Axios cancel token through useEffect cleanup code, I can implement this way when calling the axios in the component, however I would like to know if I can implement cancelToken when axios call is in separate file.
[when using axios in the component]
useEffect(() => {
const request = Axios.CancelToken.source()
const fetchPost = async () => {
try {
const response = await Axios.get(`endpointURL`, {
cancelToken: request.token,
})
setPost(response.data)
setIsLoading(false)
} catch (err) {
console.log('There was a problem or request was cancelled.')
}
}
fetchPost()
return () => request.cancel()
}, [])
[page component]
useEffect(() => {
const cancel = axios.CancelToken.source();
fetchData();
return () => {
};
}, []);
const fetchData= async () => {
try {
const payload = {
page: 0,
size: 10,
};
const {
data: { content },
} = await UserService.getUserSupplier(payload);
setSupplier(content);
} catch (err) {
console.log(err);
}
};
[UserService.js]
export const getUserSupplier = async payload => {
const url = `/user/supplier?${qs.stringify(payload)}`;
const response = await ApiService.get(url); // ApiService is just Axios I separated file because of interceptor
return response;
};

Related

React and socket IO changing route

We have a dynamic route system in our chat app in react frontend and nestjs backend. when we are not refreshing the page but going to a different route, and calling socket event, then the app goes to the previous routes where we visited before. But when we refresh the page and stay in the one route, it stays there.
the problem is, when we change the route, it remembers the previous routes where we visited and goes to that route when socket calling, when we do not refresh the page, this problem occurs.
import React, { useCallback, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useParams } from 'react-router-dom';
import { userActiveStatusApi } from '../api/auth';
import { getAllMessageApi, makeReadApi, sendMessageApi } from '../api/chat';
import { selectUserProfile } from '../redux/features/authSlice';
import { selectActiveUser, setUpdateConversation, setUpdateUnreadCount } from '../redux/features/layoutSlice';
import ChattingHomeUi from '../ui/chattingHome/ChattingHomeUi';
import { newSocket } from '../utils/socket';
import { getDateWiseMessages } from '../utils/utils';
const ChattingHome = () => {
let { chatId } = useParams();
const [currentUserProfile, setCurrentUserProfile] = useState({})
const [isLoading, setIsLoading] = useState(true);
const [messagesText, setMessagesText] = useState('')
const [allMessage, setAllMessage] = useState([])
const userProfile = useSelector(selectUserProfile)
const onlineUsers = useSelector(selectActiveUser)
const dispatch = useDispatch();
const userId = userProfile.id;
// check user online status function
function isOnline(id) {
return onlineUsers.indexOf(id) !== -1;
}
// get current user profile function
const getCurrentUserProfile = useCallback(async () => {
async function successHandler(response) {
const res = await response.json();
setCurrentUserProfile(res.user)
setIsLoading(false);
}
async function handleBadReq(response) {
let error = await response.json();
console.log(error.message);
setIsLoading(false);
}
return await userActiveStatusApi(chatId, { successHandler, handleBadReq })
}, [chatId])
// get current user all message list function
const getAllMessage = useCallback(async () => {
async function successHandler(response) {
const res = await response.json();
let sortedData = getDateWiseMessages(res)
setIsLoading(false)
setAllMessage(sortedData)
}
async function handleBadReq(response) {
let error = await response.json();
console.log(error)
setIsLoading(false);
}
return await getAllMessageApi(chatId, { userId: userId }, { successHandler, handleBadReq })
}, [userId, chatId])
// add or update message on conversations List
const updateConversationList = (res) => {
const newMessage = {
users_id: parseInt(res.receiverId),
users_profileImage: currentUserProfile.profileImage,
users_fullname: currentUserProfile.fullname,
message_Status_lastMessage: res?.content,
message_Status_lastMessageTime: res?.createdAt,
message_Status_unreadMessages: 0,
}
dispatch(setUpdateConversation(newMessage))
}
// Send message function
async function handleSubmitMessage() {
if (!messagesText.length) return;
const messageData = {
message: messagesText,
senderId: userId,
type: "text"
}
async function successHandler(response) {
const res = await response.json();
getDeliveryStatus()
updateConversationList(res.result)
setMessagesText('')
getAllMessage();
}
async function handleBadReq(response) {
let error = await response.json();
console.log(error.message);
setIsLoading(false);
}
return await sendMessageApi(chatId, messageData, { successHandler, handleBadReq })
}
const getDeliveryStatus = () => {
newSocket.on('delevered/' + userId, (res) => {
console.log(res)
})
}
// make message as read message
const makeReadMessage = useCallback(async () => {
newSocket.once('message-seen-status' + chatId, (msg) => {
console.log("red", msg);
})
const payload = {
senderId: chatId,
}
async function successHandler(response) {
dispatch(setUpdateUnreadCount(chatId))
}
async function handleBadReq(response) {
let error = await response.json();
console.log(error);
}
return await makeReadApi(userProfile.id, payload, { successHandler, handleBadReq })
}, [dispatch, chatId, userProfile.id])
useEffect(() => {
getCurrentUserProfile()
makeReadMessage()
}, [getCurrentUserProfile, makeReadMessage])
useEffect(() => {
console.log(chatId)
newSocket.on('newMessage/user/' + userId, (msg) => {
if (parseInt(msg.senderId) === parseInt(chatId)) {
makeReadMessage();
}
getAllMessage();
})
}, [chatId, makeReadMessage, getAllMessage, userId])
useEffect(() => {
getAllMessage()
}, [getAllMessage])
return (
<ChattingHomeUi
handleSubmitMessage={handleSubmitMessage}
messagesText={messagesText}
setMessagesText={setMessagesText}
allMessage={allMessage}
userProfile={userProfile}
isOnline={isOnline}
isLoading={isLoading}
currentUserProfile={currentUserProfile} />
);
};
export default ChattingHome;

React update state when click

import React, { useEffect, useState } from "react";
import { Container, Row } from "react-bootstrap";
import ListCategories from "./ListCategories";
import Hasil from "./Hasil";
import DaftarProduk from "./DaftarProduk";
import axios from "axios";
import keranjang from "../utils/keranjang";
import BASE_URL from "../utils/constata";
const Main = () => {
const [dataProduct, setDataProduct] = useState([]);
const [dataCategories, setDataCategories] = useState([]);
const [categoriesId, setCategoriesId] = useState(1);
const [listPesanan, setListPesanan] = useState([]);
const handleListCategories = (id) => {
setCategoriesId(id);
};
const handleProdukClick = async (produk) => {
keranjang(produk);
};
useEffect(() => {
const getProducts = async () => {
let responseJson = [];
try {
responseJson = await axios.get(
BASE_URL + "products?category.id=" + categoriesId
);
} catch (error) {
console.log("Ada yang " + error);
} finally {
setDataProduct(responseJson.data);
}
};
const getCategories = async () => {
let responseJson = [];
try {
responseJson = await axios.get(BASE_URL + "categories");
} catch (error) {
console.log("Ada yang " + error);
} finally {
setDataCategories(responseJson.data);
}
};
const getPesanans = async () => {
let responseJson = [];
try {
responseJson = await axios.get(BASE_URL + "keranjangs");
} catch (error) {
console.log("Ada yang " + error);
} finally {
setListPesanan(responseJson.data);
}
};
getProducts();
getCategories();
getPesanans();
}, [categoriesId]);
return (
<Container className="mt-3">
<Row>
{dataCategories && (
<ListCategories
categories={dataCategories}
handleClick={handleListCategories}
categoriesActive={categoriesId}
></ListCategories>
)}
{dataProduct && (
<DaftarProduk
produk={dataProduct}
handleClick={handleProdukClick}
></DaftarProduk>
)}
<Hasil pesanan={listPesanan}></Hasil>
</Row>
</Container>
);
};
export default Main;
How to update listPesanan, when handleProdukClick was click?
if me put listPesanan inside
useEffect(() => {
const getProducts = async () => {
let responseJson = [];
try {
responseJson = await axios.get(
BASE_URL + "products?category.id=" + categoriesId
);
} catch (error) {
console.log("Ada yang " + error);
} finally {
setDataProduct(responseJson.data);
}
};
const getCategories = async () => {
let responseJson = [];
try {
responseJson = await axios.get(BASE_URL + "categories");
} catch (error) {
console.log("Ada yang " + error);
} finally {
setDataCategories(responseJson.data);
}
};
const getPesanans = async () => {
let responseJson = [];
try {
responseJson = await axios.get(BASE_URL + "keranjangs");
} catch (error) {
console.log("Ada yang " + error);
} finally {
setListPesanan(responseJson.data);
}
};
getProducts();
getCategories();
getPesanans();
}, [categoriesId, listPesanan]);
that's causes looping to send request to server
my full code in here
Yes, your second 'solution' will cause looping, because you have listPesanan in you dependency array (The second parameter to the useEffect function), so whenever listPesanan changes, the useEffect is run again. And in fact, you are updating the value of listPesanan in the useEffect, which causes the useEffect to get triggered again, which causes you to update the value of listPesanan, and so on.
If I understand your question/code, a simple solution would just be to declare the getPesanans function outside of the useEffect hook, and then have your DaftarProduk onClick call that function. Then, remove listPesanan from the dependency array of useEffect. Your code would look like this:
import React, { useEffect, useState } from "react";
import { Container, Row } from "react-bootstrap";
import ListCategories from "./ListCategories";
import Hasil from "./Hasil";
import DaftarProduk from "./DaftarProduk";
import axios from "axios";
import keranjang from "../utils/keranjang";
import BASE_URL from "../utils/constata";
const Main = () => {
const [dataProduct, setDataProduct] = useState([]);
const [dataCategories, setDataCategories] = useState([]);
const [categoriesId, setCategoriesId] = useState(1);
const [listPesanan, setListPesanan] = useState([]);
**const getPesanans = async () => {
let responseJson = [];
try {
responseJson = await axios.get(BASE_URL + "keranjangs");
} catch (error) {
console.log("Ada yang " + error);
} finally {
setListPesanan(responseJson.data);
}
};**
const handleListCategories = (id) => {
setCategoriesId(id);
};
const handleProdukClick = async (produk) => {
keranjang(produk);
**await getPesanans();**
};
useEffect(() => {
const getProducts = async () => {
let responseJson = [];
try {
responseJson = await axios.get(
BASE_URL + "products?category.id=" + categoriesId
);
} catch (error) {
console.log("Ada yang " + error);
} finally {
setDataProduct(responseJson.data);
}
};
const getCategories = async () => {
let responseJson = [];
try {
responseJson = await axios.get(BASE_URL + "categories");
} catch (error) {
console.log("Ada yang " + error);
} finally {
setDataCategories(responseJson.data);
}
};
getProducts();
getCategories();
getPesanans();
}, [categoriesId]);
return (
<Container className="mt-3">
<Row>
{dataCategories && (
<ListCategories
categories={dataCategories}
handleClick={handleListCategories}
categoriesActive={categoriesId}
></ListCategories>
)}
{dataProduct && (
<DaftarProduk
produk={dataProduct}
handleClick={handleProdukClick}
></DaftarProduk>
)}
<Hasil pesanan={listPesanan}></Hasil>
</Row>
</Container>
);
};
export default Main;
problem
First handleProdukClick triggers another effect, keranjang.
const handleProdukClick = async (produk) => { // ⚠️ async misuse
keranjang(produk); // ⚠️ effect
// ✏️ update listPesanan here ...
};
code review
Your linked source code shows this implementation for keranjang. This code misunderstands how to effectively apply async and await. Let's fix that first.
⚠️ await..then anti-pattern doesn't assign result to variable
⚠️ 38-LOC function with mixed concerns
⚠️ Errors are swallowed so caller cannot respond to them
const keranjang = async (produk) => {
let pesanan = {
jumlah: 1,
total_harga: produk.harga,
product: produk,
};
const popUpPesanan = () => // ⚠️ nested function, no arguments
swal({
title: "Berhasil",
text: "Masuk Keranjang " + produk.nama,
icon: "success",
button: "Oke",
});
await axios // ⚠️ no return
.get(BASE_URL + "keranjangs?product.id=" + produk.id)
.then(async (res) => {
if (res.data.length === 0) {
await axios // ⚠️ no return
.post(BASE_URL + "keranjangs", pesanan)
.then(() => popUpPesanan())
.catch((error) => console.log(error)); // ⚠️ swallow error
} else {
pesanan = { // ⚠️ variable reassignment
jumlah: res.data[0].jumlah + 1,
total_harga: res.data[0].total_harga + produk.harga,
product: produk,
};
await axios // ⚠️ no return
.put(BASE_URL + "keranjangs/" + res.data[0].id, pesanan)
.then(() => popUpPesanan())
.catch((error) => console.log(error)); // ⚠️ swallow error
}
})
.catch((error) => console.log(error)); // ⚠️ swallow error
};
First write keranjang from a high-level.
✅ Reusable get, add, and increase functions decouple separate concerns
✅ Return Promise so handleProduckClick can know when it is complete
✅ Pass arguments to functions instead of reassigning variables
✅ Do not swallow error messages with .catch
const keranjang = async (produk) => {
const pesanan = await get(produk.id)
if (pesanan.length === 0)
return add(produk).then(() => popUpPesanan(produk))
else
return increase(pesanan[0], produk).then(() => popUpPesanan(produk))
}
✅ Implement get, add, increase
✅ Each function returns a Promise
const get = (id) =>
axios.get(`${BASE_URL}keranjangs?product.id=${id}`).then(res => res.data)
const add = (produk) =>
axios.post(`${BASE_URL}keranjangs`, {
jumlah: 1,
total_harga: produk.harga,
product: produk,
})
const increase = (pesanan, produk) =>
axios.put(`${BASE_URL}keranjangs/${pesanan.id}`, {
jumlah: pesanan.jumlah + 1,
total_harga: pesanan.total_harga + produk.harga,
product: produk,
})
popUpPesanan accepts a produk argument
const popUpPesanan = (produk) =>
swal({
title: "Berhasil",
text: "Masuk Keranjang " + produk.nama,
icon: "success",
button: "Oke",
})
fix #1
With all of that fixed, handleProdukClick can appropriately respond to the keranjang call.
const handleProdukClick = async (produk) => {
try {
await keranjang(produk) // ✅ await
setListPesanan(await getPesanans())// ✅ await and set
} catch (err) {
console.log(err) // ✅ caller handles error
}
};
You don't need async and await for this. It's easier to write
const handleProdukClick = (produk) => {
keranjang(produk).then(setListPesanan).catch(console.error)
}
fix #2
Now you have to move getPesanans out of the useEffect call in your component and decouple the mixed concerns like you did with keranjang...
import { getProducts, getCategories, getPesanans } from "./api"
const Main = () => {
const [dataProduct, setDataProduct] = useState([])
const [dataCategories, setDataCategories] = useState([])
const [categoriesId, setCategoriesId] = useState(1)
const [listPesanan, setListPesanan] = useState([])
const handleListCategories = (id) => {
setCategoriesId(id)
}
const handleProdukClick = (produk) => {
keranjang(produk).then(setListPesanan).catch(console.error)
}
useEffect(() => {
getProducts(categoriesId).then(setDataProduct).catch(console.error)
getCategories().then(setDataCategories).catch(console.error)
getPesanans().then(setListPesanan).catch(console.error)
}, [categoriesId]) // ✅ no infinite loop
return (...)
}
api
Define a reusable api module so each component does not need to concern itself with axios, building URLs, or picking apart responses.
✅ Reusable functions separate concerns
✅ .then(res => res.data) allows caller to access data directly
✅ Errors are not swallowed
✅ axios.create makes instance so you don't have to add BASE_URL to everything
import axios from "axios"
import BASE_URL from "../utils/constata";
const client = axios.create({ baseURL: BASE_URL })
const getProducts = (categoriesId) =>
client.get("/products?category.id=" + categoriesId).then(res => res.data)
const getCategories = () =>
client.get("/categories").then(res => res.data)
const getPesanans = () =>
client.get("/keranjangs").then(res => res.data)
export { getProducts, getCategories, getPesanans }
homework
✏️ Move get, add, and increase functions you wrote in keranjang to the api module.
✏️ Remove unnecessary BASE_URL
✏️ Rename them accordingly and add them to the export list
✏️ Any time you see axios spilling into your other components, refactor and move them to your api module
✏️ Consider using transformRequest and transformResponse in your axios config so you don't have to add .then(res => res.data) to each request
✏️ Consider decoupling swal and keranjang. keranjang can move to the api module and swal can be called from your component.
// api.js
const keranjang = async (produk) => {
const pesanan = await get(produk.id)
if (pesanan.length === 0)
return add(produk)
else
return increase(pesanan[0], produk)
}
// component.js
const Main = () => {
// ...
const handleProdukClick = (produk) => {
keranjang(produk)
.then(setListPesanan)
.then(_ => swal({
title: "Berhasil",
text: "Masuk Keranjang " + produk.nama,
icon: "success",
button: "Oke",
}))
.catch(console.error)
}
// ...
}
✏️ util/keranjang is now an empty module and can be removed

Stop axios request call in react

I'm trying to stop axios request.
I use useInterval(custom hooks)(I referenced a website) to request api.
So I stop it with useState and it's totally stopped when i set interval like 1000ms.
however, when i set interval like 100ms then i can't stop api request. it's stopped after 3seconds or something.
So i tried to use if statement. but it's not working as i expected.
and I also checked Network from development tool on chrome
and the request Status was getting changed from pending to 200
and when all the request's Status change to 200, then it stopped.
I really want to know how i can stop API request properly.
my code is like this
useInterval
import { useEffect } from "react";
import { useRef } from "react";
const useInterval = (callback, delay) => {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
const tick = () => {
savedCallback.current();
};
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
export default useInterval;
API calling
const [API_DATA, setAPI_DATA] = useState(null);
const [apiStart, setApiStart] = useState(false);
const [spinner, setSpinner] = useState(false);
//Request API
const getAPI = useCallback(async () => {
if (apiStart) {
await axios
.get(API_URL, {
headers: Header,
})
.then(response => {
setAPI_DATA(response.data);
setSpinner(false);
})
.catch(error => {
init();
console.log("error");
});
}
}, [API_DATA, spinner]);
// start API
const start_API = () => {
setSpinner(true);
setApiStart(true);
};
//stop API
const stop_API = () => {
setSpinner(false);
alert("API STOP");
setApiStart(false);
};
//using useInterval
useInterval(
() => {
if (apiStart) return getAPI();
},
apiStart ? 100 : null
);
Go take a look at the axios documentation at https://axios-http.com/docs/cancellation. I would remove the if(apiStart) as this does not do much. I would possibly rewrite your this method as follows:
const [data, setData] = useState(null);
const [spinnerActive, setSpinnerActive] = useState(false);
const controller = new AbortController();
const getAPI = useCallback(async () => {
setSpinnerActive(true);
await axios
.get(API_URL, {
headers: Header,
signal: controller.signal
})
.then(response => {
setData(response.data);
setSpinnerActive(false);
})
.catch(error => {
setSpinnerActive(false);
console.log("error");
});
}, [data, spinnerActive]);
useInterval(
() => {
getApi()
},
apiStart ? 100 : null
);
Then when you want to abort the request, call controller.abort()

too many request on react using axios on get api

export async function onGetNews(){
let data = await axios.get(`${Link}/news`, {
params: {
limit: 1
}
}).then(res => {
return (res.data)
});
return data
}
I tried a lot of solutions and I didn't find a good one. I use limit and other ... and when I use useEffect with export function it gives me an error
export function OnGetServices(){
const [service, setService] = useState([])
useEffect(() => {
setTimeout(async () => {
let data = await axios.get(`${Link}/services`, {}).then(res => {
setService(res.data)
});
}, 1000);
console.log(data);
}, []);
console.log(service);
return service;
}
Why are you doing .then() when you are using async/await? Try this:
export async function onGetNews(){
let res= await axios.get(`${Link}/news`, {
params: {
limit: 1
}
});
return res.data
}
And your react snippet can be:
export function OnGetServices(){
const [service, setService] = useState([])
useEffect(() => {
setTimeout(async () => {
let res = await axios.get(`${Link}/services`, {})
setService(res.data);
console.log(res.data);
}, 1000);
}, []);
}
And if you don't really need the setTimeout, you could change the implementation to:
export function OnGetServices(){
const [service, setService] = useState([])
useEffect(() => {
const fn = async () => {
let res = await axios.get(`${Link}/services`, {})
setService(res.data);
console.log(res.data);
}
fn();
}, []);
}
Async/await drives me crazy either. I wrote a solution, but I'm not sure if it performs good practices. Feedback appreciated.
https://codesandbox.io/s/react-boilerplate-forked-y89eb?file=/src/index.js
If it's a hook then it has to start with the "use" word. Only in a hook, or in a Component, you can use hooks such as useEffect, useState, useMemo.
export function useService(){ //notice the "use" word here
const [service, setService] = useState([])
useEffect(() => {
setTimeout(async () => {
let data = await axios.get(`${Link}/services`, {}).then(res => {
setService(res.data)
});
}, 1000);
console.log(data);
}, []);
console.log(service);
return service;
}
const SomeComponent = () => {
const service = useService();
}

Infinite loop when setting and using state in a `useCallback` that is being called from a `useEffect`

I would like to fetch data when the user changes.
To do this I have a useEffect that triggers when the user changes, which calls a function to get the data.
The problem is that the useEffect is called too often because it has a dependency on getData and getData changes because it both uses and sets loading.
Are there ways around this, while still retaining getData as a function, as I call it elsewhere.
const getData = useCallback(async () => {
if (!loading) {
try {
setLoading(true);
const { error, data } = await getDataHook();
if (error) {
throw new Error("blah!");
}
} catch (error) {
const message = getErrorMessage(error);
setErrorMessage(message);
setLoading(false);
}
}
}, [loading]);
...
useEffect(() => {
const callGetData = async () => {
await getData();
};
callGetData();
}, [user, getData]);
Try moving loading from useCallback to useEffect. Something like this:
const getData = useCallback(async () => {
try {
const { error, data } = await getDataHook();
if (error) {
throw new Error("blah!");
}
} catch (error) {
const message = getErrorMessage(error);
setErrorMessage(message);
}
}, []);
...
useEffect(() => {
const callGetData = async () => {
await getData();
};
if (!loading) {
setLoading(true);
callGetData();
setLoading(false);
}
}, [user, getData, loading]);
The loading flag is something that the call sets, and shouldn't be effected by it, so remove it from the useEffect(), and getData() functions.
const getData = useCallback(async () => {
try {
setLoading(true);
const { error, data } = await getDataHook();
if (error) {
throw new Error("blah!");
}
} catch (error) {
const message = getErrorMessage(error);
setErrorMessage(message);
} finally {
setLoading(false); // not related, but this would remove loading after an error as well
}
}, []);
useEffect(() => {
const callGetData = async () => {
await getData(user);
};
callGetData();
}, [user, getData]);

Resources