Cannot get the input value when using textinput #160
-
Code: package tui
// A simple program demonstrating the text input component from the Bubbles
// component library.
import (
"fmt"
"log"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
)
type errMsg error
type model struct {
textInput textinput.Model
err error
}
var inputPlaceholder string
func initialModel() model {
ti := textinput.New()
ti.Placeholder = inputPlaceholder
ti.Focus()
ti.CharLimit = 156
ti.Width = 20
return model{
textInput: ti,
err: nil,
}
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyEnter, tea.KeyCtrlC, tea.KeyEsc:
fmt.Println(m)
return m, tea.Quit
}
// We handle errors just like any other message
case errMsg:
m.err = msg
return m, nil
}
m.textInput, cmd = m.textInput.Update(msg)
return m, cmd
}
var inputTitle string
func (m model) View() string {
return fmt.Sprintf(
inputTitle+"\n\n%s\n\n%s",
m.textInput.View(),
"(esc to quit)",
) + "\n"
}
func Input(title string, placeholder string) string {
inputTitle = title
inputPlaceholder = placeholder
m := initialModel()
p := tea.NewProgram(m)
if err := p.Start(); err != nil {
log.Fatal(err)
}
fmt.Println()
fmt.Println("value:", m.textInput.Value())
return m.textInput.Value()
} Console messages:
I am confused that why the value is not updated finally? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
At a first glance your code probably works fine, but after |
Beta Was this translation helpful? Give feedback.
-
I think it would be very valuable for the community to have these 2 lines integrated into the 2 input examples as part of this repository. |
Beta Was this translation helpful? Give feedback.
At a first glance your code probably works fine, but after
p.Start
you're retrieving the input from the initial model, which will always remain empty: it gets replaced by a new model every timeUpdate
gets called. You can either letUpdate
operate on a pointer-receiver, so you keep modifying your original model, or implement another way to store the final value before callingtea.Quit
.