Home > Back-end >  React - I have to click a button twice to display api data
React - I have to click a button twice to display api data

Time:12-09

I would like to display API data on a button click. My state is set to an empty array initially and I guess that's why it shows an empty array at first click, but what could I write differently to show data on first click ? After the initial click it works.

My code:

const Search = () => {

    const [textInput, setTextInput] = useState('');
    const [tickers, setTickers] = useState([]);
    const [prices, setPrices] = useState([]);
    const [isClicked, setIsClicked] = useState(false);

    const inputHandler = (e) => {
        setTextInput(e.target.value); 
    }

    const showData = async (e) => {
        e.preventDefault();
        const url = `https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=${textInput}&apikey=${process.env.REACT_APP_ALPHA_VANTAGE_API_KEY}`
      
        try {
            const data = await axios.get(url);
            
            if(data) {
                setPrices([data.data['Monthly Time Series']['2021-11-30']]);
            }
        } catch(err) {
           console.log(err)
        }
        console.log(prices);
        setIsClicked(true);
        setTextInput('');
    }

    return (
        <StyledSearch>
            <h1>Security Price Monitor App </h1>
            <form onSubmit={submitSearch}>
                <input type="text" value={textInput} onChange={inputHandler} placeholder='Enter Ticker'/>
                <button type="submit" onClick={showData}>Search</button>
            </form>
            {isClicked &&
                <Chart tickers = {tickers} setTickers={setTickers} prices={prices} setPrices={setPrices}/>
            }
        </StyledSearch>

    )
}

CodePudding user response:

Try to change your conditional rendering condition to:

{prices.length > 0 && (
    <Chart
      tickers={tickers}
      setTickers={setTickers}
      prices={prices}
      setPrices={setPrices}
    />
  )}

I think that you can remove the isClicked state. It is redundant.

  • Related