Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

reactjs - Irritating API bug in react, cannot figure it out

I have an API call set up with two search buttons from one input box. Each button adds something using state to the api call which the code below should demonstrate. The calls both work fine independently and display the correct information.

If a user has clicked the 'wild cards' button the results show but then on clicking the 'standard set' button the results don't re-render the correct results until the button is pressed a second time (vice versa for both buttons).

I have removed the un-related code as to condense the question

Any help appreciated

Home.js - with api call, state and functions passed down as props to the searchBar

export const Home = () => {
        const [searchTerm, setSearchTerm] = useState('')
        const [wild, setWild] = useState('')
        let accessToken;
    
        const getCards = async() => {
            try {
                await getToken()
                const response = await fetch(`https://eu.api.blizzard.com/hearthstone/cards/?collectible=1${wild}&textFilter=${searchTerm}&locale=en-US$access_token=${accessToken}`, {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }})
            const data = await response.json()
            const {cards} = data
            if (cards){
                const newCards = cards.map((card) => { ** some data i want ** }
                  
                setCards(newCards)
            }
            } catch (error) {
                console.log(error)
            } 
        }

    return (
             <SearchBar     getCards = {getCards}
                            setWild = {setWild}
                            setSearchTerm = {setSearchTerm} />
            </div>
        </div>  
    )
 }

SearchBar Component - again condensed for the sake of this question

export const SearchBar = (props) => {
    const searchBox = useRef('')
   
    const handleClickWild = (e) => {
        e.preventDefault()
        props.setWild('')
        props.getCards()
    }

    const handleClickStandard = (e) => {
        e.preventDefault()
        props.setWild('&set=standard')
        props.getCards()
    }

    const handleChange = (e) => {
        props.setSearchTerm(e.target.value)
    }

    return (
        <form>
            <input className = 'input-search'
            type = 'text'
            placeholder = 'Search for Cards by Name...'
            ref = {searchBox} 
            onChange = {handleChange} />
            <div className = 'search-buttons'>
                <input type = 'submit' className = 'button-search' onClick = {handleClickWild} value = 'Wild Cards' />
                <input type = 'submit' className = 'button-search' onClick = {handleClickStandard} value = 'Standard Set' />
            </div>
        </form>
    )
}

question from:https://stackoverflow.com/questions/65943846/irritating-api-bug-in-react-cannot-figure-it-out

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to use useEffect hook here.

You can use wild in dependency array and whenever you change the value of searchTerm use effect will automatically call your getCards function.

As you mentioned in the comment you want to show changes when user search anything then keep the wild in simple variable and add search term in useEffect and if you want you can add both in the useEffect dependency array

useEffect(()=> {
   getCards()
}, [searchTerm])

Just remove explicite calls of props.getCards after setting wild from SearchBar component.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...