Skip to content
Advertisement

React API call in useEffect runs only when parameter is hardcoded, not when using state

Hi I am creating an app where a user can search for a book and put it on a shelf depending on which shelf the user clicks on. Currently the user can type a query and many results can get displayed. The user can open a dropdown on a book and click on a shelf (in the dropdown) to select a shelf for that book.

I want to call a method that will update the shelf of a book. It works only if the shelfType is hardcoded however (shelfTypes are ‘wantToRead’, ‘read’, ‘currentlyReading’). What I want to happen is that the user clicks on a shelf and that shelf is set as the local state variable shelfType in SearchPage. Then once the shelfType changes, the method to update the shelf of a book will run (it makes an API call to a backend).

But for some strange reason I can only update the shelf if I hardcode the shelf type into the update method, not when I use the value of the state shelfType. What am I doing wrong? I hope this question makes sense.

SearchPage.js

JavaScript

Book.js

JavaScript

ButtonDropDown.js

JavaScript

Advertisement

Answer

Cause you’re “Want to Read” text in choices is different

JavaScript

Based on this // update works if I run update(currentBook, 'wantToRead').then((res) => console.log(res));

“wanToRead” is not equal to “Want to Read”

Advertisement