mardi 23 mai 2023

Set an onChange for checkbox in React?

I'm trying to update a record by selecting a checkbox when a book has been read. Whenever I refresh the page, the checkbox returns as unchecked. How can I store the selected checkbox and see it checked after the page is refreshed? Thanks in advance!

import React, { useState } from 'react';
import axios from 'axios';

const Book = ( {title, author, id, getBooks}) => {
  const [finished, setFinished] = useState(false)

  const handleChange = async (e) => {
    const { name, value } = e.target;

    await axios.put(`http://localhost:3000/api/v1/books/${id}`, {
        book: {
          [name]: value,
          finished: !finished
        },
      })
  };

  return (
    <tr>
      <td>
        <input
          type="text"
          name="title"
          defaultValue={title}
          onChange={handleChange}
          className="form-control"
        />
      </td>
      <td>
        <input
          type="text"
          name="author"
          defaultValue={author}
          onChange={handleChange}
          className="form-control"
        />
      </td>
      <td className="text-center">
        <div className="form-check form-check-inline pt-2">
          <input
            type="checkbox"
            name="finished"
            defaultChecked={finished}
            className="form-check-input"
            onChange={() => setFinished(!finished)}
          />
          <label className="form-check-label">
            Done
          </label>
        </div>
      </td>
    </tr>
  )
}

export default Book



Aucun commentaire:

Enregistrer un commentaire