shahawi273
shahawi273

Reputation: 25

Page does not reload on state change inside jsx

I have seen several questions with the same title but not the same problem,

I wrote some react code and inside return method's jsx, inside select onchange I called a function that setstate but the page will not reload although I made sure the state is changed

jsx code inside return:

<select defaultValue={book.shelf} onChange={(e) => this.handleChange(e, book)}

code inside contructor

constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);}

code inside component

 handleChange = (e, book) => {
 BooksAPI.update(book, e.target.value).then(this.setState(
     { value: e.target.value, book: book },
     () => console.log(this.state.value)
   ));

};

Knowing that this.state.value prints correctly and the value is returned from the API and it is different from the previous state's value

What could be the problem,

Any help appreciated.

Edit: My full select code

<select defaultValue={book.shelf} onChange={(e) => handleChange(e, book)}>
                        <option value="move" disabled>
                          Move to...
                        </option>
                        <option value="currentlyReading">
                          Currently Reading
                        </option>
                        <option value="wantToRead">Want to Read</option>
                        <option value="read">Read</option>
                        <option value="none">None</option>
                      </select>

Edit 2:

This is my state

 state = {
    books: [],
    value: '',
    book: {},
    update: false,
  };

Final edit:

To prevent confusion the problem was with my UI unrelated to this code

Upvotes: 2

Views: 333

Answers (1)

Joshua
Joshua

Reputation: 651

The problem is this

handleChange = (e, book) => {
 BooksAPI.update(book, e.target.value).then(this.setState(
     { value: e.target.value, book: book },
     () => console.log(this.state.value)
   ));

Change it to this

handleChange = (e, book) => {
 BooksAPI.update(book, e.target.value).then(() => {
    this.setState(
     { value: e.target.value, book: book },
     () => console.log(this.state.value)
   )
 });

Upvotes: 1

Related Questions