Home > Software design >  React post object in an array
React post object in an array

Time:05-22

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)

CodePudding user response:

Just use an array instead of the string in the category. And append the array if checked otherwise filters the array.

const [category, setCategory] = useState([]);
const handleChange = (e)=>{
    setCategory(state=>{
        if(e.target.checked){
            state.push(e.target.value);    
            return [...state]
        }else{
            return [...state.filter(item=>item!==e.target.value)]
        }
    })
}
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={handleChange} value="Category1" />
    <input type="checkbox" onChange={handleChange} value="Category2" />
    <input type="checkbox" onChange={handleChange} value="Category3" />

CodePudding user response:

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}/>
  })}</>

  • Related