點燈坊

失くすものさえない今が強くなるチャンスよ

Preparing Body Object for fetch()

Sam Xiao's Avatar 2022-11-09

When using fetch() for REST POST, we can easily prepare Body Object on Alpine.

Version

Alpine 3.10

Body Object

body000

The body Object is shown by Alpine.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body x-data="{ id: 0, name: 'Sam' }">
    <input x-model="id" />
    <input x-model="name" />
    <button @click="onClick($data)">Submit</button>
  </body>
  <script>
    let onClick = ({ id, name }) => {
      let body = { id, name }
      console.log(body)
    }
  </script>
</html>

Line 9

<body x-data="{ id: 0, name: 'Sam' }">
  <input x-model="id" />
  <input x-model="name" />
  <button @click="onClick($data)">Submit</button>
</body>
  • x-data:define data Object for component
  • x-model:two-way data binding the input value to the state
  • @click:fire onClick() on click event and use $data to pass data Object to function

Line 15

let onClick = ({ id, name }) => {
  let body = { id, name }
  console.log(body)
}
  • Destructure states from parameter
  • Combine states to body Object

Conclusion

  • Remember to use $data to pass the data Object to the event handler. It could prevent using this to access data Object
  • We can use Object Destructure from parameter to get states and collect them to body Object