Jesse James
Jesse James

Reputation: 75

ReactJS , setState issue onChange event

in my child component I set input with onChange:

<input onChange={this.handlePlaylistTermChange} defaultValue={'New Playlist'}/>

which then sets the state of what the user has put in the input

handlePlaylistTermChange(e){
    this.setState({playlistName: e.target.value });

then when the button is clicked I pass that value to a method that uses props to call the parent class method that takes in that state when the button is clicked

save() {
        if (this.state.playlistName === null || this.state.playlistName === "") {
            this.props.onSave('New Playlist') ;
        } else {
            this.props.onSave(this.state.playlistName);
        }
    }

which calls in the parent class:

savePlaylist(name) {
        let trackUrIs = [];

        console.log(name);
        let playlist =this.state.playlistTracks;

        playlist.forEach(track =>{
            trackUrIs.push(track.URI);

        });
        console.log( "passed in name"+ name);
        console.log(trackUrIs);

        Spotify.savePlaylist(trackUrIs,name);


        console.log('whats happening here?' + this.state.playlistName);
        this.setState({playlistTracks: []});
        this.setState({playlistName: ''});

This all works great except I need the Playlist name value to change back to "new playlist" but no matter what I seem to do the value that happened on the onChange remains. I have tried resetting the state in the child and passing that up to the parent and no matter what I cant get the onchange value to reset to "new playlist" after the save button has been clicked.

Upvotes: 1

Views: 5110

Answers (2)

SMM
SMM

Reputation: 1

constructor(props) {
    super(props);

    this.state = { clickedItem: "show here..." };
    this.ItemClick = this.ItemClick .bind(this);        
}
ItemClick = (e) => {
    this.setState({ clickedItem: e.target.value});
}

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281616

DefaultValue is only assigned to the input at the time of mounting and cannot be updated with a change, you should rather use a controlled input and set the value based on the state and in order to define a defaultValue, initialise it in state

state={
   playList: 'New Playlist'
}

<input onChange={this.handlePlaylistTermChange} value={this.state.playList}/>

Now onChange of the input field, you can update the playList state to reflect the updated value in input

handlePlaylistTermChange =(e) => {
    this.setState({playList: e.target.value});
}

Upvotes: 1

Related Questions