-
Hi guys, I just started learning So basically error handling is not working as I expected this is my code for setting axios I have this // Core
import axios, { AxiosResponse, AxiosError } from 'axios';
import * as Sentry from '@sentry/browser';
// Types
import { SegmentInterface } from '../types/api';
import { checkAuth } from '../services/check-auth';
// Configurations
import { API_URL } from '../configuarion';
export const client = axios.create({ baseURL: API_URL });
const api = ({ ...options }, segment: SegmentInterface = { event: null, context: null}) => {
checkAuth();
const onSuccess = (response: AxiosResponse) => {
//Segment Tracking
// eslint-disable-next-line no-prototype-builtins
if (window.hasOwnProperty('analytics') && segment && segment.event) {
const event = segment.event;
const context = segment.context;
window.analytics.track(event, context);
}
return response;
}
const onError = (error: AxiosError | Error) => {
Sentry.captureException(error);
throw error
}
client.defaults.headers.common.Authorization = `Bearer ${window.localStorage['access_token']}`;
return client(options).then(onSuccess).catch(onError);
}
export default api; Then I use this function to make the request like this export const updateUser = async (data: UserInterface) => {
const response = await api({
url: '/iam/v1/account/',
method: 'PUT',
data
}, {
event: 'Account Profile Updated', context: {
id: data.id,
avatar: data.avatar,
email: data.username,
first_name: data.first_name,
last_name: data.last_name,
opted_in_marketing: data.opted_in_marketing
}
})
return response
};
export const useUpdateUser = (config: any) => {
return useMutation(updateUser, config);
}
// Core
import { useState } from 'react';
import { useQueryClient } from 'react-query';
// Core Components
import { Form, Input, Switch, Button, Row, Col, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
// Icons
import { MailOutlined, UserOutlined } from '@ant-design/icons';
// Types
import { UserInterface } from '../../../../types/user';
// Hooks
import api from '../../../../hooks/api';
import { useUpdateUser } from '../../../../hooks/user';
// Services
import { getHash } from '../../../../services/helpers';
// Styles
import './account.module.less';
// Configuration
export interface AccountProps {
user: UserInterface;
}
export function Account(props: AccountProps) {
const { user } = props;
const queryClient = useQueryClient();
const { isLoading, isError, mutate, data } = useUpdateUser({
onSuccess: (updatedUser: UserInterface) => {
if (updatedUser && updatedUser.id) {
queryClient.setQueryData(['user'], updatedUser);
queryClient.invalidateQueries(['user']);
}
},
onError: (error: any) => {
console.log(error, 'error');
},
});
const [fileList, setFileList] = useState([
{
uid: '-1',
name: 'image.png',
url: user.avatar,
},
]);
const onFinish = (values: UserInterface) => {
let userData = {
...user,
...values,
avatar: fileList.length ? fileList[0].url : user.avatar,
};
mutate(userData);
};
const onChange = ({ fileList: newFileList }: any) => {
setFileList(newFileList);
};
const onPreview = async (file: any) => {
let src = file.url;
if (!src) {
src = await new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(file.originFileObj);
reader.onload = () => resolve(reader.result);
});
}
const image = new Image();
image.src = src;
const imgWindow = window.open(src);
imgWindow?.document.write(image.outerHTML);
};
const onRequest = async (item: any) => {
const response: any = await api({
url: `/frontend/v1/upload/loginaccount/${user.id}/${getHash(9)}-${
item.file.name
}`,
method: 'PUT',
headers: {
'Content-Type': item.file.type,
},
data: item.file,
});
setFileList([
{
uid: item.file.uid,
name: item.file.name,
url: response.data.url,
},
]);
};
console.log(isError);
if (isError) {
return null;
}
return (
<Form
name="account"
className="account-form"
size="large"
layout="vertical"
initialValues={{
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
opted_in_marketing: user.opted_in_marketing,
}}
onFinish={onFinish}
>
<Row gutter={16}>
<Col span={24}>
<ImgCrop rotate quality={1}>
<Upload
accept="image/*"
maxCount={1}
customRequest={onRequest}
listType="picture-card"
fileList={fileList}
onChange={onChange}
onPreview={onPreview}
>
{fileList.length < 1 && '+ Upload'}
</Upload>
</ImgCrop>
</Col>
<Col span={24}>
<Form.Item
label="Email"
name="username"
rules={[{ required: true, message: 'Email is required.' }]}
>
<Input allowClear prefix={<MailOutlined />} placeholder="Email" />
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item
label="First Name"
name="first_name"
validateStatus={
data && data.data && data.data.first_name ? 'error' : undefined
}
help={data && data.data && data.data.first_name[0]}
>
<Input
allowClear
prefix={<UserOutlined />}
placeholder="First Name"
/>
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item label="Last Name" name="last_name">
<Input
allowClear
prefix={<UserOutlined />}
placeholder="Last Name"
/>
</Form.Item>
</Col>
<Col span={24}>
<Form.Item
name="opted_in_marketing"
valuePropName="checked"
label="I'd like to receive emails about product updates and company news."
>
<Switch checkedChildren="ON" unCheckedChildren="OFF" />
</Form.Item>
</Col>
<Col span={24}>
<Form.Item>
<Button
loading={isLoading}
type="primary"
htmlType="submit"
className="account-form-button"
>
Update Profile
</Button>
</Form.Item>
</Col>
</Row>
</Form>
);
}
export default Account; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Found the answer it was just an issue with axios interceptors just remove the useEffect(() => {
setLoggedIn(checkAuth());
client.interceptors.request.use(
(config) => {
setLoggedIn(checkAuth());
return config;
},
(error) => {
setLoggedIn(checkAuth());
Sentry.captureException(error);
return error;
}
);
return history.listen(() => {
setLoggedIn(checkAuth());
});
}, []); |
Beta Was this translation helpful? Give feedback.
Found the answer it was just an issue with axios interceptors just remove the
client.interceptors.response
..... the other interceptors are fine like theclient.interceptors.request