modih65067
modih65067

Reputation: 129

Old state is losing while doing search in React

So I'm trying to build search feature for a website and I'm facing an issue where when a specific search is done the old state is not there, and if you delete a character is deleted I don't have the old state and doesn't not filter anything.

Here is my function:

function filterSearch(state, query) {
    const orders = state.orders.filter((order) =>
        order.id.toLowerCase().includes(query.toLowerCase())); // this filters the state

    state.orders = orders; // this is redux state but you can think it as a setState
}

Upvotes: 0

Views: 127

Answers (2)

nbg123
nbg123

Reputation: 59

you have to maintain two state for this, one state would be of the initial order then you can put that state into the local state which you can use to display the orders and always search on the initial state so that user will always get the correct result, something like following

const Table = ({ initailSearch }) => {
  const [data, setData] = React.useState(initailSearch);
  const [query, setQuery] = React.useState("");
  const handleChange = (e) => {
    setQuery(e.target.value);
  };
  useEffect(() => {
    let filterData = initailSearch;
    if (query.length > 0) {
      filterData = initailSearch.filter((item) => {
        return item.id.toLowerCase().includes(query.toLowerCase());
      });
    }
    setData(filterData);
  }, [query]);

  return (
    <>
      <input onChange={handleChange} />
      <table>
        <thead>
          <tr>
            <th>order</th>
          </tr>
          {data.map((item) => {
            return (
              <tr key={item.id}>
                <td>{item.id}</td>
              </tr>
            );
          })}
        </thead>
      </table>
    </>
  );
};

working code sandbox link

Upvotes: 1

Lu&#237;s Mestre
Lu&#237;s Mestre

Reputation: 1938

The problem is that you're storing the original state and overwriting the same. These are my suggestions

First Approach: storing filtered orders

function filterSearch(state, query) {
    const orders = state.orders.filter((order) => {
        const id = order.id.toLowerCase();
        return id.includes(query.toLowerCase()));
    });

    state.filteredOrders = orders;
}

Basically you'll create a new state to store the filtered orders. That way the state orders will maintain the original list

Second Approach: returning filtered

function filterSearch(state, query) {
    const orders = state.orders.filter((order) => {
        const id = order.id.toLowerCase();
        return id.includes(query.toLowerCase()));
    });

    return orders;
}

This way instead of storing the filtered data or overwriting the original data, use the function to return the filtered data and use it where you need it

Upvotes: 1

Related Questions