Attempting to develop a custom hook in TypeScript for managing errors & API requests, but encountering a type error where a property does not exist on type 'any[]'
Here is the code for the hook:
import axios from 'axios';
import { useState } from 'react';
interface params {
method: string;
body: object;
url: string;
}
interface reqParam {
message: string;
errors: string[];
}
const useRequest = ({url, method, body}: params) => {
const [errors, setErrors] = useState(null);
const doRequest: () => Promise<{} | null> = async () => {
try {
const response = await axios[method](url, body);
return response.data;
} catch (err) {
setErrors(
<div className="alert alert-danger">
<h4>Oooops.....</h4>
<ul className="mu-0">
{err.response.data.errors.map((e: reqParam) => <li key={e.message}>{e.message}</li>)}
</ul>
</div>
)
}
};
return [doRequest, errors];
};
export default useRequest;
If a demonstration of the expected response output is necessary, please let me know and I can provide an example.
The sign up file includes the following code:
import { useState } from "react";
import useRequest from "../../hooks/use-request";
const signUp = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const {doRequest, errors} = useRequest({
url: '/api/users/signup',
method: 'post',
body: {
email, password
}
});
const onSubmit = async (e: { preventDefault: () => void; }) => {
e.preventDefault();
doRequest();
};
return (
<form onSubmit={onSubmit} className="container">
<h1>signup</h1>
<div className="form-group">
<label>email</label>
<input
value={email}
onChange={e => setEmail(e.target.value)}
className="form-control"
/>
</div>
<div className="form-group">
<label>password</label>
<input
value={password}
onChange={e => setPassword(e.target.value)}
type="password"
className="form-control"
/>
</div>
{errors}
<button className="btn btn-primary">Sign Up</button>
</form>
)
}
export default signUp;
Any assistance in identifying the issue would be greatly appreciated. The information provided should be sufficient, but if more details are needed, please don't hesitate to reach out. Thank you