Reputation: 125
I have a input in all the pages. I am tryin to clear the input placeholders after send the item.name (setSearchSchool) to handleSuggestionClick. If I clear setSearchSchool in handleSuggestionClick, I am not goint to the next page. How do I clean the input placeholder?
SEARCH COMPONENT (CODE UPDATED)
import React, { useEffect, useState } from "react";
import api from "../../api/index";
import "./index.css";
import { useLocation } from "wouter";
export default function Search() {
const [searchSchool, setSearchShool] = useState("");
const [showSuggestions, setShowSuggestions] = useState(false);
const [allSchools, setAllSchools] = useState([]);
const [, pushLocation] = useLocation();
useEffect(() => {
(async () => {
const data = await api.getSchools();
setAllSchools(data);
})();
}, []);
const resultsAllSchools = !searchSchool
? allSchools
: allSchools
.map(item => ({
name: item.name,
codeSchool: item.codeSchool,
address: item.address,
city: item.city,
nameRegion: item.nameRegion,
codeRegion: item.codeRegion,
latitud: item.latitud,
longitud: item.longitud
}))
.filter(school => school.name.toLowerCase().includes(searchSchool));
const handleOnchange = e => {
e.preventDefault();
const lowerCase = e.target.value.toLowerCase();
setSearchShool(lowerCase);
setShowSuggestions(true);
if (e.target.value === "" || null) {
setShowSuggestions(false);
}
};
const handleSuggestionClick = item => {
setSearchShool(item.name);
localStorage.setItem("myLocalStore", JSON.stringify(item));
pushLocation(`/centre/${item.codeSchool}`);
};
return (
<>
<section className="section">
<div className="search">
<input
className="select"
type="text"
placeholder="Cerca el teu centre educatiu... "
value={searchSchool}
onChange={handleOnchange}
></input>
<div className="svg_search">
<svg
height="25"
viewBox="0 0 21 21"
width="25"
xmlns="http://www.w3.org/2000/svg"
>
<g
fill="none"
fillRule="evenodd"
stroke=" #0099ff"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="8.5" cy="8.5" r="5" />
<path d="m17.571 17.5-5.571-5.5" />
</g>
</svg>
</div>
</div>
<ul>
{showSuggestions &&
resultsAllSchools.map((item, i) => (
<li
key={i}
title={item.name}
onClick={() => handleSuggestionClick(item)}
>
<p className="school_name">{item.name}</p>
<p className="school_address">
{item.address} - {item.city}
</p>
</li>
))}
</ul>
</section>
</>
);
}
Upvotes: 1
Views: 371
Reputation: 4938
If you want to clear out the form, then don't set the state then, use it directly from the parameters of the handleSuggestionClick
function.
const handleSuggestionClick = item => {
localStorage.setItem("myLocalStore", JSON.stringify(item));
pushLocation(`/centre/${item.codeSchool}`);
};
Upvotes: 1