Отправка формы (Formik) на сервер (json-server)
Пытаюсь отправить форму созданную в Formik на json-server но получаю предупреждение мол я использую не функцию а ожидается функция. и отправка не происходи. ни как не пойму что именно делаю не так.
const HeroesAddForm = () => {
const request = useHttp()
const dispatch = useDispatch()
const onSubmitForm = (values) => {
const newHero = {id: uuidv4(), ...values}
request(`http://localhost:3001/heroes`, 'POST', JSON.stringify(newHero))
.then(res => console.log(res, 'Отправка успешна'))
.then((res) => dispatch(heroCreate(res)))
.catch(err => console.log(err))
}
return (
<Formik
initialValues = {{
name: '',
description: '',
element: ''
}}
onSubmit = {(values) => onSubmitForm(values)}>
<Form className="border p-4 shadow-lg rounded">
<div className="mb-3">
<MyTextInput
label="Имя нового героя"
required
type="text"
name="name"
className="form-control"
id="name"
placeholder="Как меня зовут?"/>
</div>
<div className="mb-3">
<label htmlFor="description" className="form-label fs-4">Описание</label>
<Field
as="textarea"
required
name="description"
className="form-control"
id="description"
type="text"
placeholder="Что я умею?"
style={{"height": '130px'}}/>
</div>
<div className="mb-3">
<label htmlFor="element" className="form-label">Выбрать элемент героя</label>
<Field
required
className="form-select"
id="element"
name="element"
as="select">
<option >Я владею элементом...</option>
<option value="fire">Огонь</option>
<option value="water">Вода</option>
<option value="wind">Ветер</option>
<option value="earth">Земля</option>
</Field>
</div>
<button type="submit" className="btn btn-primary">Создать</button>
</Form>
</Formik>
)
}
useHttp:
import { useCallback } from "react";
export const useHttp = () => {
const request = useCallback(async (url, method = 'GET', body = null, headers = {'Content-Type': 'application/json'}) => {
try {
const response = await fetch(url, {method, body, headers});
if (!response.ok) {
throw new Error(`Could not fetch ${url}, status: ${response.status}`);
}
const data = await response.json();
return data;
} catch(e) {
throw e;
}
}, []);
return {request}
}
Ответы (1 шт):
Автор решения: Yuriy Sidorov
→ Ссылка
вы неверно вызываете, у вас в request сейчас объект, сделайте:
const { request } = useHttp()
