So I am making a blog application. I have used an axios inceptors concept name is api.js -
import axios from 'axios';
import { API_NOTIFICATION_MESSAGES, SERVICE_URLS } from '../constants/config';
const API_URL = 'http://localhost:8000';
const axiosInstance = axios.create({
baseURL: API_URL,
timeout: 10000,
headers: {
'content-type': 'application/json',
},
});
axiosInstance.interceptors.request.use(
function (config) {
// if (config.TYPE.params) {
// config.params = config.TYPE.params
// } else if (config.TYPE.query) {
// config.url = config.url + '/' + config.TYPE.query;
// }
return config;
},
function (error) {
return Promise.reject(error);
},
);
axiosInstance.interceptors.response.use(
function (response) {
// Stop global loader here
return processResponse(response);
},
function (error) {
// Stop global loader here
return Promise.reject(processError(error));
},
);
///////////////////////////////
// If success -> returns { isSuccess: true, data: object }
// If fail -> returns { isFailure: true, status: string, msg: string, code: int }
//////////////////////////////
const processResponse = (response) => {
if (response?.status === 200) {
return { isSuccess: true, data: response.data };
} else {
return {
isFailure: true,
status: response?.status,
msg: response?.msg,
code: response?.code,
};
}
};
///////////////////////////////
// If success -> returns { isSuccess: true, data: object }
// If fail -> returns { isError: true, status: string, msg: string, code: int }
//////////////////////////////
const processError = async (error) => {
if (error.response) {
//request made and server responded wit a status other than that falls out of the range 2.x.x
console.log('ERROR IN RESPONSE: ', error.toJSON());
return {
isError: true,
msg: API_NOTIFICATION_MESSAGES.responseFailure,
code: error.response.status,
};
} else if (error.request) {
//request made but no response was received
console.log('ERROR IN RESPONSE: ', error.toJSON());
return {
isError: true,
msg: API_NOTIFICATION_MESSAGES.requestFailure,
code: '',
};
} else {
//something happended in writting up request that triggers an error
console.log('ERROR IN RESPONSE: ', error.toJSON());
return {
isError: true,
msg: API_NOTIFICATION_MESSAGES.networkError,
code: '',
};
}
};
const API = {};
for (const [key, value] of Object.entries(SERVICE_URLS)) {
API[key] = (body, showUploadProgress, showDownloadProgress) =>
axiosInstance({
method: value.method,
url: value.url,
data: body,
responseType: value.responseType,
onUploadProgress: function (progressEvent) {
if (showUploadProgress) {
let percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total,
);
showUploadProgress(percentCompleted);
}
},
onDownloadProgress: function (progressEvent) {
if (showDownloadProgress) {
let percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total,
);
showDownloadProgress(percentCompleted);
}
},
});
}
export { API };
This is my config.js page -
// API NOTIFICATION MESSAGES
export const API_NOTIFICATION_MESSAGES = {
loading: {
title: 'Loading...',
message: 'Data is being loaded. Please wait',
},
success: {
title: 'Success',
message: 'Data successfully loaded',
},
requestFailure: {
title: 'Error!',
message: 'An error occur while parsing request data',
},
responseFailure: {
title: 'Error!',
message:
'An error occur while fetching response from server. Please try again',
},
networkError: {
title: 'Error!',
message:
'Unable to connect to the server. Please check internet connectivity and try again.',
},
};
// API SERVICE URL
// SAMPLE REQUEST
// NEED SERVICE CALL: { url: "/", method: "POST/GET/PUT/DELETE" }
export const SERVICE_URLS = {
userLogin: { url: '/login', method: 'POST' },
userSignup: { url: '/signup', method: 'POST' },
getAllPosts: { url: '/posts', method: 'GET', params: true },
getRefreshToken: { url: '/token', method: 'POST' },
uploadFile: { url: 'file/upload', method: 'POST' },
createPost: { url: 'create', method: 'POST' },
deletePost: { url: 'delete', method: 'DELETE', query: true },
getPostById: { url: 'post', method: 'GET', query: true },
newComment: { url: '/comment/new', method: 'POST' },
getAllComments: { url: 'comments', method: 'GET', query: true },
deleteComment: { url: 'comment/delete', method: 'DELETE', query: true },
updatePost: { url: 'update', method: 'PUT', query: true },
};
Finally this is my Login.jsx page -
import { Box, TextField, Button, styled, Typography } from '@mui/material';
import { useState } from 'react';
import { API } from '../../service/api';
const Component = styled(Box)`
width: 400px;
margin: auto;
box-shadow: 5px 2px 5px 2px rgb(0 0 0/ 0.6);
`;
const Image = styled('img')({
width: 100,
display: 'flex',
margin: 'auto',
padding: '50px 0 0',
});
const Wrapper = styled(Box)`
padding: 25px 35px;
display: flex;
flex: 1;
overflow: auto;
flex-direction: column;
& > div,
& > button,
& > p {
margin-top: 20px;
}
`;
const LoginButton = styled(Button)`
text-transform: none;
background: #fb641b;
color: #fff;
height: 48px;
border-radius: 2px;
`;
const SignupButton = styled(Button)`
text-transform: none;
background: #fff;
color: #2874f0;
height: 48px;
border-radius: 2px;
box-shadow: 0 2px 4px 0 rgb(0 0 0 / 20%);
`;
const Text = styled(Typography)`
color: #878787;
font-size: 12px;
`;
const Error = styled(Typography)`
font-size: 10px;
color: #ff6161;
line-height: 0;
margin-top: 10px;
font-weight: 600;
`;
const signupInitialValues = {
name: '',
username: '',
password: '',
};
const Login = () => {
const imageURL =
'https://www.sesta.it/wp-content/uploads/2021/03/logo-blog-sesta-trasparente.png';
const [signup, setSignup] = useState(signupInitialValues);
const [error, showError] = useState('');
const [account, toggleAccount] = useState('login');
const onInputChange = (e) => {
setSignup({ ...signup, [e.target.name]: e.target.value });
};
const signupUser = async () => {
let response = await API.userSignup(signup);
console.log(response);
if (response.isSuccess) {
showError('');
setSignup(signupInitialValues);
toggleAccount('login');
} else {
showError('Something went wrong! please try again later');
}
};
const toggleSignup = () => {
account === 'signup' ? toggleAccount('login') : toggleAccount('signup');
};
return (
<Component>
<Box>
<Image src={imageURL} alt="login"></Image>
{account === 'login' ? (
<Wrapper>
<TextField variant="filled" label="Enter Username" />
<TextField variant="filled" label="Enter Password" />
{error && <Error>{error}</Error>}
<LoginButton variant="contained">LOGIN</LoginButton>
<Text style={{ textAlign: 'center' }}>OR</Text>
<SignupButton
onClick={() => toggleSignup()}
style={{ marginBottom: 50 }}
>
Create an account
</SignupButton>
</Wrapper>
) : (
<Wrapper>
<TextField
variant="filled"
onChange={(e) => onInputChange(e)}
label="Enter Name"
/>
<TextField
variant="filled"
onChange={(e) => onInputChange(e)}
label="Enter Username"
/>
<TextField
variant="filled"
onChange={(e) => onInputChange(e)}
label="Enter Password"
/>
{error && <Error>{error}</Error>}
<SignupButton onClick={() => signupUser()}>SIGN UP</SignupButton>
<Text style={{ textAlign: 'center' }}>OR</Text>
<LoginButton variant="contained" onClick={() => toggleSignup()}>
Already have an account
</LoginButton>
</Wrapper>
)}
</Box>
</Component>
);
};
export default Login;
Then, whenever I'm testing it by clicking sign up, it is showing this error.
Please resolve my issue.
I was trying to create user sign up successfully

e.target.nameto determine the field. FYI your API should respond with a 400 status and appropriate error message in such casessetSignup((prev) => ({ ...prev, [e.target.name]: e.target.value })). See Why React useState with functional update form is needed?