0

Want to search through added todos and display only searched todos.

function App() {
    const [text, setText] = useState("Add a task")
    const [task, setTask] = useState(getLocalItem())   
     
    const changeText = (event) => {

        setText(event.target.value)
    }
    const submitHandler = (event) => {
        console.log("submitted");
        event.preventDefault();
        setTask([...task, text])

        setText("")
    }
    
    const removeTask =(a)=>{
        const finalData = task.filter((curEle,index)=>{
            return index !== a;
        })

        setTask(finalData)
      }
    useEffect(()=>{
        localStorage.setItem("lists",JSON.stringify(task))
    },[task])

tried adding functionality using filter() but wasnt able to succeed. Want to search through added todos and display only searched todos. full code here: https://codeshare.io/ZJRDkd

  • isn't that `task.filter` already a good start for search functionality? maybe add a [string comparison](https://stackoverflow.com/questions/1179366/is-there-a-javascript-strcmp) or something instead of exact one. – Bagus Tesa Sep 27 '22 at 06:09

1 Answers1

0

You may try includes method.

Example:

task.filter(t => t.includes(searchText));

So, add an input box for search text:

const [searchText, setSearchText] = useState("");
const [filteredTasks, setFilteredTasks] = useState(tasks);

const handleSearchTextChange = e => {
  setSearchText(e.target.value)
}

useEffect(() => {
  setFilteredTasks(tasks => tasks.filter(t => t.includes(searchText)))
},[searchText])

In your render, just added

<input value={searchText} onChange={handleSearchTextChange} placeholder="search"/>

Use the filteredTasks to display the list.

nightElf
  • 502
  • 2
  • 4