0

When creating a search input in react it worked successfully but when removes search word from input it remove all data from array and return no thing

i need to search but when i done return array again

const [todos, setTodos] = useState([]); const searchTodo = (todoitem) => { const searchedTodo = todos.filter((todo) => { if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) { return todo; } }); setTodos(searchedTodo); 

};

2
  • 1
    Add another state of filteredTodos. Because as soon as you filter the todos, you lose the original dataset. Commented Feb 3, 2022 at 14:02
  • Can you tell me how please Commented Feb 3, 2022 at 14:06

2 Answers 2

1

You can either create a new variable for filtered todos or use it at body without any extra field.

First, let's take a took at the first solution:

const [todos, setTodos] = useState([]); const [filteredTodos, setFilteredTodos] = useState([]); const searchTodo = (todoitem) => { const searchedTodo = todos.filter((todo) => { if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) { return todo; } return searchedTodo; }); useEffect(() => { setFilteredTodos(searchTodo(todoitem)); }, [todoitem]); \\ todoitem is the text you want to search with 

The other way is just using the function in return body like below:

const [todos, setTodos] = useState([]); const searchTodo = (todoitem) => { const searchedTodo = todos.filter((todo) => { if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) { return todo; } return searchedTodo; }); return ( <div> {searchTodo(todoitem).map(todo => (<div>{todo}</div>))} </div> ); 
Sign up to request clarification or add additional context in comments.

Comments

0

Based on ldruskis comment:

const [todos, setTodos] = useState([]); const [filtered, setFiltered] = useState([]); const searchTodo = (todoitem) => { const searchedTodo = todos.filter((todo) => { if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) { return todo; } }); setFiltered(searchedTodo); 

Then you add a conditional render such as:

{filtered.length > 0 ? <render filtered> : <render todos> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.