React update state when click - reactjs

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

Related

React custom http-hook abortController() bug

I have this custom http hook with abort when you try to go to a different page (I saw it in a tutorial but I am not truly sure I need it). When I fetch data with it and useEffect(), I have this error on the backend but the request is executed and everything is as planned. My question is, how to improve my code so it does not throw this error and do I need this functionality with abortController() ?
http-hook.ts
import { useCallback, useRef, useEffect } from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { selectError, showError } from "src/redux/error";
import { selectLoading, startLoading, stopLoading } from "src/redux/loading";
export const useHttpClient = () => {
const dispatch = useDispatch();
const error = useSelector(selectError);
const loading = useSelector(selectLoading);
const activeHttpRequests: any = useRef([]);
const sendRequest = useCallback(
async (url, method = "GET", body = null, headers = {}) => {
dispatch(startLoading());
const httpAbortCtrl = new AbortController();
activeHttpRequests.current.push(httpAbortCtrl);
try {
const response = await fetch(url, {
method,
body,
headers,
signal: httpAbortCtrl.signal,
});
const responseData = await response.json();
activeHttpRequests.current = activeHttpRequests.current.filter(
(reqCtrl) => reqCtrl !== httpAbortCtrl
);
if (!response.ok) {
throw new Error(responseData.message);
}
dispatch(stopLoading());
return responseData;
} catch (err) {
dispatch(showError(err.message));
dispatch(stopLoading());
throw err;
}
},
[]
);
useEffect(() => {
return () => {
activeHttpRequests.current.forEach((abortCtrl: any) => abortCtrl.abort());
};
}, []);
return { loading, error, sendRequest };
};
UserInfo.tsx
import React, { Fragment, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useHttpClient } from "src/hooks/http-hook";
import classes from "./UserInfo.module.css";
const UserInfo = () => {
const { sendRequest } = useHttpClient();
const [currentUser, setCurrentUser] = useState<any>();
const userId = useParams<any>().userId;
useEffect(() => {
const fetchCurrentUser = async () => {
try {
const responseData = await sendRequest(
`http://localhost:5000/api/user/${userId}`
);
setCurrentUser(responseData.user);
console.log("currentUser ", currentUser);
} catch (err) {
console.log(err);
}
};
fetchCurrentUser();
}, [sendRequest ,userId]);
return currentUser ? (
<Fragment>
<div className={classes.cover} />
<div className={classes.user_info}>
<img
alt="user_img"
src={`http://localhost:5000/${currentUser.image}`}
className={classes.user_img}
/>
<div className={classes.text}>
<p>
Name: {currentUser.name} {currentUser.surname}
</p>
<p>Email: {currentUser.email}</p>
<p>Age: {currentUser.age}</p>
</div>
</div>{" "}
</Fragment>
) : (
<p>No current user</p>
);
};
export default UserInfo;
Backend
getCurrentUser.ts controller
const getCurrentUser = async (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
const userId = req.params.userId;
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError("Could not fetch user", 500);
return next(error);
}
res.json({ user: user.toObject({ getters: true }) });
};

React - useEffect based on another useEffect

I'm trying to understand how useEffect works.
I have two callApi: "callApiDialer" is based on response of "callApiManager", for get id from list.
But "currentLeadId" state at first called obviously is null.
How can call "callApiDialer" when currentLeadId is not null?
import React, { useState, useEffect } from 'react';
const [loading, setLoading] = useState(true);
const [apiManager, setApiManager] = useState([]);
const [apiDialer, setApiDialer] = useState([]);
const [currentLeadId, setCurrentLeadId] = useState(null);
// CALL API
const callApiManager = async () => {
try {
const response = await api.get(`/api/manager/op/1`);
setCurrentLeadId(response.data.dialer_list[0].id);
setApiManager(response.data);
} catch (err) {
alert("fetchApiManager " + err.response.status);
}
}
const callApiDialer = async () => {
try {
const response = await api.get(`/api/manager/lead/${currentLeadId}`);
setApiDialer(response.data.lead);
setLoadingModal(false);
} catch (err) {
alert("fetchApiSources " + err.response.status);
}
}
useEffect(() => {
callApiManager();
}, [])
useEffect(() => {
console.log(currentLeadId); // <-- here get first null and after currentLeadId
if(currentLeadId) {
callApiDialer();
setLoading(false);
}
}, [currentLeadId])
You could have just one function that call both, therefore there would be only one useEffect.
// CALL API
const callBothApisAtOnce= async () => {
try {
const op = await api.get(`/api/manager/op/1`);
const response = await api.get(`/api/manager/lead/${op.data.dialer_list[0].id}`);
// rest of your logic...
} catch (err) {
alert("err" + err);
}
}
useEffect(() => {
callBothApisAtOnce()
}, [])
you can use axios's promise base functionality
axios.get(`/api/manager/op/1`).then(res => {
setCurrentLeadId(response.data.dialer_list[0].id);
setApiManager(response.data);
axios.get(`/api/manager/lead/${response.data.dialer_list[0].id}`).then(res1 =>{
setApiDialer(res1.data.lead);
setLoadingModal(false);
}
}

UseEffect mutiple re-renders after async api call and make changes in UI after 1 sec of first call

I'm making a Quiz app, using API from (Trivia api),
Issues is - As soon as the api call is made the state is changes 3 times and my UI data changes 2 times in 1 second.
I think the issue is related to useEffect even though i'm adding empty dependency in useEffect.
can anybody explain why is it happening?
Layout.js
import { useEffect, useState } from 'react'
import { Outlet } from 'react-router-dom'
import Header from '../Componenets/Header/Header'
import ProgressBar from '../Componenets/ProgressBar/ProgressBar'
import QuizMain from '../Componenets/QuizMain/QuizMain'
function Layout() {
const [questionAre, setQuestionsAre] = useState([])
const [currentQuestion, setCurrentQuestion] = useState(0)
const changeCurrentQuestion = (value) => {
setCurrentQuestion(value)
}
useEffect(() => {
const QuizFetch = async () => {
try {
const res = await fetch(
'https://the-trivia-api.com/api/questions?categories=food_and_drink,general_knowledge&limit=10&region=AU&difficulty=easy',
)
const data = await res.json()
const transformData = data.map((item) => {
const newarray = item.incorrectAnswers
return {
options: newarray,
question: item.question,
correctAnswer: item.correctAnswer,
}
})
setQuestionsAre(transformData)
} catch (err) {
console.log(err, 'err in getting data')
}
}
QuizFetch()
}, [])
return (
<div className="Layout">
<Header />
<ProgressBar
changeCurrentQuestion={changeCurrentQuestion}
currentQuestion={currentQuestion}
questionAre={questionAre}
/>
{/* <QuizMain
changeCurrentQuestion={changeCurrentQuestion}
currentQuestion={currentQuestion}
questionAre={questionAre} /> */}
<Outlet context={[changeCurrentQuestion, currentQuestion, questionAre]} />
</div>
)
}
export default Layout
Since react 18 and the lifecycle in dev mode you have to use the abortController.
The signal will jump to the catch and then you will only have one successfull api call
useEffect(() => {
const abortController = new AbortController();
const QuizFetch = async () => {
try {
const res = await fetch(
'https://the-trivia-api.com/api/questions?categories=food_and_drink,general_knowledge&limit=10&region=AU&difficulty=easy',
{
signal: abortController.signal,
},
)
const data = await res.json()
const transformData = data.map((item) => {
const newarray = item.incorrectAnswers
return {
options: newarray,
question: item.question,
correctAnswer: item.correctAnswer,
}
})
setQuestionsAre(transformData)
} catch (err) {
if (abortController.signal.aborted) return;
console.log(err, 'err in getting data')
}
}
QuizFetch()
return () => {
abortController.abort();
};
}, [])

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;

Axios cancelToken in useEffect cleanup

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;
};

Resources