Search code examples
reactjsreact-hooksuse-state

React state setting timing for conditional rendering


Currently, I am working on a simple React Exercise.

The I am trying to conditionally render a certain part of the jsx based on a certain state.

Basically, my code looks like this

const ShopList = (props) => {

    const [isLoading, setIsLoading] = useState(false)
    const [isEnd, setIsEnd] = useState(false)

    const handleButtonClick = ()=>{
        setIsLoading(true)
        axios.get('https://codingapple1.github.io/shop/data2.json')
        .then((result)=>{
            setTimeout(()=>props.addData(result.data),2000)
        })
        .then(()=>{
            setIsEnd(true)
        })
        .catch((e)=>{
            console.log(e)
            setIsLoading(false)
        })
    }

    return(
        <div className="container">
            <div className="row">
                {props.shoes.map((shoe,i) => (
                    <Product shoe={shoe} ind={i+1} key={shoe.id}/>
                ))}
            </div>
            {isLoading && <h3>Loading....</h3>}
            {!isEnd && <button className="btn btn-light" onClick={handleButtonClick}>More Items</button>}
        </div>
    )
}

export default ShopList;

The thing is that I am having trouble locating my setIsLoading(false) so that I can hide the <h3>Loading...</h3> after two seconds.

In which part of the handleButtonClick function should I put setIsLoading(false)?


Solution

  • Answering your question, you most likely need to hide "Loading" in both cases: if the request was successful and not. So you could do this in the finally section like this:

    axios.get(...)
      .then(...)
      .catch(...)
      .finally(() => setIsLoading(false));