Home > front end >  Old state is losing while doing search in React
Old state is losing while doing search in React

Time:02-17

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
}

CodePudding user response:

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

CodePudding user response:

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

  • Related