i’m new to react and I’m trying to update the CategoryId in the state object. In the handleCategoriesChange method, I have attempted to update the state with the option selected from the dropdown with the index. In the database, it is just saving the default value which is 1 but not the option that is chosen. I would appreciate any help thanks.
CreatePost.jsx
import React, { useContext, useEffect, useState } from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { AuthContext } from "../helpers/AuthContext";
function CreatePost() {
const { authState } = useContext(AuthContext);
const [listOfCategories, setListOfCategories] = useState([]);
const [image, setImage] = useState();
const [selectedIndex, setSelectedIndex] = useState(null);
const [initialValues, setInitialValues] = useState({
title: "",
post: "",
ingredients: "",
image: "",
CategoryId: 1,
});
let navigate = useNavigate();
useEffect(() => {
if (!localStorage.getItem("accessToken")) {
navigate("/login");
}
axios.get("http://localhost:3001/categories").then((response) => {
setListOfCategories(response.data);
});
}, []);
const validationSchema = Yup.object().shape({
title: Yup.string().required("You must input a Title!"),
post: Yup.string().required(),
ingredients: Yup.string().required(),
});
const onSubmit = (data) => {
axios
.post("http://localhost:3001/posts", data, {
headers: { accessToken: localStorage.getItem("accessToken") },
})
.then((response) => {
navigate("/");
});
}
const handleCategoriesChange = (event) => {
const index = event.target.selectedIndex;
setSelectedIndex(index);
setInitialValues({
categoryId: index,
});
};
return (
<div className="createPostPage">
<Formik
initialValues={initialValues}
onSubmit={onSubmit}
validationSchema={validationSchema}
encType="multipart/form-data"
>
<Form className="formContainer">
<label>Title: </label>
<ErrorMessage name="title" component="span" />
<Field
autocomplete="off"
id="inputCreatePost"
name="title"
placeholder="(Ex. Title...)"
/>
<label>Post: </label>
<ErrorMessage name="post" component="span" />
<Field
autocomplete="off"
id="inputCreatePost"
name="post"
placeholder="(Ex. Post...)"
/>
<label>ingredients: </label>
<ErrorMessage name="ingredients" component="span" />
<Field
autocomplete="off"
id="inputCreatePost"
name="ingredients"
placeholder="(Ex. ingredients...)"
/>
<Field
as="select"
name="CategoryId"
onChange={handleCategoriesChange}
>
<option value="none">None</option>
{listOfCategories.map((item, index) => (
<option value={item.category_name} key={index}>
{item.category_name}
</option>
))}
</Field>
{selectedIndex !== null && <p>Selected index: {selectedIndex}</p>}
<button type="submit"> Create Post</button>
</Form>
</Formik>
</div>
);
}
export default CreatePost;