Is there a good way to convert HTML form data to javascript object of elixir map?

I want to get form data from a liveview hook.

# heex
<.form let={f} for={:result} id="form" phx-hook="hook">
  <%= text_input f, :field %>
  <%= submit "submit %>
</.form>
// hook
const hook = {
  mount() {
    const button = this.el.querySelector('button')
    button.addEventListener('click', () => {
      const formData = new FormData(this.el)
      for (const [key, value] of formData.entries()) {
        console.log(key)
        console.log(value)
      }
    })
  }
}

Then the key of formData is result[field].
I want to get a object like {result: {field: any}} or an elixir map like %{"result" => %{"field" => any}}.
Is there a good way to convert form data to javascript object of elixir map?

You should already be receiving an Elixir map in your Phoenix endpoint so I am not sure I get your question, can you clarify further what do you want to happen but it does not happen?

1 Like