Home > Software design >  I have an output and I want to display it in array upto five values
I have an output and I want to display it in array upto five values

Time:06-29

I have output in setSearchHistory(search); and i am displaying it in History: {searchHistory} Currently I am able to log current value and on changing out put updated value is getting displayed. I want the previous output and new output to be displayed like an array and this goes up to five places.

    const [city, setCity] = useState(null);
    const [search, setSearch] = useState("Dehradun");
    const [searchHistory, setSearchHistory] = useState([]);

    useEffect ( () => {
        const fetchApi = async () => {
            const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid=7938d9005e68d8b258a109c716436c91`
            const response = await fetch(url);  
            const resJson = await response.json();
            setCity(resJson.main);
        };
        fetchApi();
},[search] )

    const handleClick = event => {
        event.preventDefault();
        setSearchHistory(search);
        };

return(
        <>
            <div className="box">
                <div className="inputData">
                <input
                id="btnc"
                type="search" 
                value={search}
                className="inputFeild" 
                onChange={ (event) => { setSearch(event.target.value) }}
               />
               <button onClick={handleClick}>Click</button>
                </div>
             <input className="is"></input>
             <h3 className="tempmin_max">
                  History: {searchHistory}
                </h3>
           {!city ? (
            <p className="errorMsg">Enter City Name</p>
           ) : (
            <div>
               
                <div className="info">
                <h2 className="location">
                <i className="fa-solid fa-street-view"> </i>{search}
                </h2>
                <h1 className="temp">
                {city.temp}
                </h1>
                <h3 className="tempmin_max">
                   Min : {city.temp_min} | Max : {city.temp_max}
                </h3>
                </div>
                <div className="wave -one"></div>
                <div className="wave -two"></div>
                <div className="wave -three"></div>
            </div>
            ) }
            </div>
        </>
    ) 
}

export default Tempapp;```

CodePudding user response:

you can do like this:

let arr = [];

const handleClick = event => {
  event.preventDefault();
  arr.push(search)
  setSearchHistory(arr);
};

Now there is a array in searchHistory. You need to use the map function to display the search history.

  • Related