EmmE
EmmE

Reputation: 37

Save the previous search when I go back with the page React

My app returns results via API when a search is performed. For each result there is a detail link. Clicking on the link and going back what I searched for is not saved, the search bar is empty. You have to rewrite the previous search to select another result. I would like the general search to be saved when going back.

function GoogleBooksSearch() {
    const [book, setBook] = useState("");
    const [result, setResult] = useState([]);
    const apiKey = ("MY API")

    function handleChange(event) {
        const book = event.target.value;
        console.log(event.target.value);
        setBook(book);
    }
    function handleSubmit(event) {
        event.preventDefault();
        axios.get("https://www.googleapis.com/books/v1/volumes?q=" + book + "&key=" + apiKey + "&maxResults=20")
            .then(data => {
                console.log(data.data.items);
                setResult(data.data.items);
            })
    }

    return (
        <div>
            <div className="hero-container">
                <h1>Search your book</h1>
                <p>Discover the best books ever</p>
                <form onSubmit={handleSubmit}>
                    <div className='container'>
                        <div>
                            <input onChange={handleChange} className="form" autoFocus placeholder="Enter the title of the book" type="text" />
                            <div style={{ marginTop: '20px' }}></div>
                            <div className='d-grid gap-2 '>
                                <input type="submit" value="SEARCH" className="btn btn-primary btn-lg mx-auto" />
                            </div>


                        </div>
                    </div>
                </form>
            </div>

I'm using the .map function to filter the results and the react-router link to open the "details" page.

{result.map(book => ( ------

                                <Link className="btn btn-primary mt-auto"
                                    to={
                                        pathname: '/details',
                                 }>
                                    View
                                </Link>

Upvotes: 3

Views: 4026

Answers (1)

Lavish Kumar
Lavish Kumar

Reputation: 136

I would suggest to implement a caching library and use its rehidration process it will be more efficient and will have higher compatability, but for a quick hackish way way to implement this is to presist your search query and its results in localStorage (will persist even after browser closed) or sessionStorage (can be session specific), and while rendering the search component rehydrate the states from the Session/Local storage.

Further also you can use Memorization by using React Memo hooks to integrate the momo component with cache to improve stability and performance

Something like this could help you (follow the comments)

//PERSITST THE SEARCH HERE
  const {searchQuery,searchResults} = JSON.parse(window.sessionStorage.getItem("searchDetails"));
  
   const [book, setBook] = useState(searchQuery ? searchQuery : "" );
    const [result, setResult] = useState( searchResults ? searchResults:[]);
    const apiKey = ("MY API")
    
    function handleChange(event) {
        const book = event.target.value;
        console.log(event.target.value);
        setBook(book);
    }
    function handleSubmit(event) {
        event.preventDefault();
        axios.get("https://www.googleapis.com/books/v1/volumes?q=" + book + "&key=" + apiKey + "&maxResults=20")
            .then(data => {
                console.log(data.data.items);
                setResult(data.data.items);

// STORE THE DATA HERE 
               window.sessionStorage.setItem("searchDetails",JSON.stringify({searchQuery:book,searchDetails:data.data.items}))
            })
    }

    return (
        <div>
            <div className="hero-container">
                <h1>Search your book</h1>
                <p>Discover the best books ever</p>
                <form onSubmit={handleSubmit}>
                    <div className='container'>
                        <div>
                            <input onChange={handleChange} className="form" autoFocus placeholder="Enter the title of the book" type="text" />
                            <div style={{ marginTop: '20px' }}></div>
                            <div className='d-grid gap-2 '>
                                <input type="submit" value="SEARCH" className="btn btn-primary btn-lg mx-auto" />
                            </div>


                        </div>
                    </div>
                </form>
            </div>

Upvotes: 2

Related Questions