'React post object in an array
I need with fetch In react post object in an array to json file like this "category": ["1", "2", "3"] I don't understand it, in my code I just post in one line "category": "1". By the way I need post through checkbox.
my code
const [category, setCategory] = useState("");
const handleSubmit = (e) =>{
e.preventDefault();
const movie = {category};
fetch('http://localhost:8000/movies', {
method: 'POST',
headers: {"Content-Type" : "application/json" },
body: JSON.stringify(movie)
}).then(() => {
alert('WEll DONE');
})
}
<input type="checkbox" onChange={(e) => setCategory(e.target.value)} value="Category1"/>
<input type="checkbox" onChange={(e) => setCategory(e.target.value)} value="Category2"/>
<input type="checkbox" onChange={(e) => setCategory(e.target.value)} value="Category3"/>
Thank you in advance)
Solution 1:[1]
Each time you select a category, it overwrites any existing category.
Many ways to handle this, one is:
const [categories, setCategories] = useState({Category1: false, Category2: false, Category3: false});
const setCategory = (c, checked) => {
setCategories(cs => ({...cs, [c]: checked}));
};
console.log("categories", categories);
const handleSubmit = (e) =>{
e.preventDefault();
const movie = {categories};
fetch('http://localhost:8000/movies', {
method: 'POST',
headers: {"Content-Type" : "application/json" },
body: JSON.stringify(movie)
}).then(() => {
alert('WEll DONE');
})
}
return <>{Object.entries(categories).map(([c, checked]) => {
return <input value={c} key={c} type="checkbox" onChange={(e) => setCategory(c, e.target.checked)} checked={checked}/>
})}</>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Igor Loskutov |
