I have React app. In this app I have page with list of image categories which I get from local server and second page with posts. I also created a form
that adds new post in local server. In this form I have four input
: ( title
, category_id
, description
, image
).
In input category_id
I write number id
of category. But now I need that there was not input
but there was select
with titles of category, which I get from server using API method GET
. And I tried to make such a select.
但是我的服务器响应错误:
必须输入category_id
这是因为:
- I pass to the server
title
category, but I should passId
category. Title should be just show us name post inselect
but I passid
to server. - Component
SelectCategory
not related withFormData
. Therefore value which is selectedSelectCategory
will not appear inFormData
and then will not appear inbody
methodhandleSubmit
.
如何解决这个问题?
response from serever(list of categories which I get in const data
):
{"data":
[{"id":20,"title":"auto"},
{"id":21,"title":"sport"},
{"id":23,"title":"new"}
]}
AddPost.js:
const AddPost = () => {
const formRef = useRef();
const [category, setCategory] = useState(''); // <-- category which I select in select will fall here
const [categories, setCategories] = useState([]); // <-- a list of existing categories will fall here
useEffect(() => {
fetchData();
}, []);
async function fetchData() { // <-- get List of categories
const data = await api(`${listRoute}`, { method: 'GET'});
setCategories(data.data.map(item => item.title)); // <-- now I set title of category in select
}
const handleSubmit = async (event) => { // <-- send form to local server
const data = new FormData(formRef.current); // <-- value from my from will fall here
event.preventDefault();
const response = await apiImage(`${imageRoute}`, {
method: 'POST',
body: data,
});};
const upadateSelectCategory = e => { // <-- choose category in select in form
setCategory(e.target.value);
};
return (
<div>
<form onSubmit={handleSubmit} ref={formRef}>
<input type="text" name="title"/>
<input type="text" name="description"/>
<input type="file" name="image" accept="image/*"/>
/*<input type="text" name="category_id"/>*/ // <-- Instead this input now I write SelectCategory:
<SelectCategory upadateSelectCategory={upadateSelectCategory} categories={categories} value={category} />
<button type="submit">Add</button>
</form>
</div>
);
};
SelectCategory.js:
export default (props) => {
return (
<div>
<select onChange={props.upadateSelectCategory} value={props.value}>
<option value="">-- Category --</option>
{props.categories.map(item => <option key={item}>{item}</option>)}
</select>
</div>
);}