Home > front end >  Save recent searches react js
Save recent searches react js

Time:10-25

Hi I m building a commerce app using react and I want to save recent searches made by users like this :

Recent searches example

I will be grateful if you could help me

thank you

CodePudding user response:

You can save it to local storage.

https://programmingwithmosh.com/react/localstorage-react/

see an example here and try to apply the same thing for "history" local storage.

CodePudding user response:

Save searches into to the local storage just like that

function App() {
  const [history,sethistory]= useState({})

  useEffect(()=>{
    recover();
  },[])
  const recover=()=>{
     let data = JSON.parse(localStorage.getItem('history'));
     this.setState({history: data.history});
  }
  const onChangeHandler =(e)=>{
        e.preventDefault();

        this.setState({input: e.target.value});
    }

  const saveToStorage=()=>{
        //local storage only takes in key value pair so you would have to serialize it.
        let history = this.state.history ? this.state.history : {history: []};

        history.history.push({text:this.state.input, link:'store linke here'});

        localStorage.setItem('history', JSON.stringify(history));
  }
  return (
  <div>
    <input onChange={onChangeHandler}/>
      <Button onClick={saveToStorage}>
        Save
      </Button>
      <div className="your-side-bar">
          {this.state.history ? this.state.history.map((item) => {
              return (
                //render as state changes
                <Link to={item.link}>{item.text}</Link>
                )
          }) : 'no history'}
        </div>
  </div>
  );
}
  • Related