Home > Enterprise >  Push array from one page to another in React
Push array from one page to another in React

Time:06-03

I am currently building an application where the user can search for a wide selection of movies and then have the option to bookmark them in a favorite page.

Currently, I have managed to build an array of movies after pressing the favorite button but not to push them to the next page of favorites.

I would appreciate any tips and tricks along the way to solve this problem!

App.js

import React from "react";
import Header from "./Header";
import {Route, Routes} from 'react-router-dom'
import Favourites from "./views/Favourites";
import Home from "./views/Home";
import About from "./views/About";

function App() {
    
    return (
    <>
        <Header />
        <div>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/favourites" element={<Favourites />} />
                <Route path="/about" element={<About />} />
            </Routes>
        </div>
        
    </>
    )
}

export default App;

Home.js

import React, { useState, useEffect } from 'react';
import SearchField from '../components/SearchField';
import MovieList from '../components/MovieList';

const Home = () => {

     const [movies, setMovies] = useState([]);
     const [searchInput, setSearchInput] = useState ('')
     const [favouriteMovies, setFavouriteMovies] = useState([])

     const handleFavourites = (movie) => {
         favouriteMovies.push(movie)
         console.log(favouriteMovies)
     }

         const getMovies = async (searchInput) => {
             const url = `http://www.omdbapi.com/?s=${searchInput}&apikey=87aa1413`;

             const res = await fetch(url);
             const resJson = await res.json();

             if (resJson.Search){
                 setMovies(resJson.Search)
             } else {
                
             }

         };

         useEffect(() => {
             getMovies(searchInput);
         }, [searchInput]);


    return ( 
        <>
             <SearchField searchInput={searchInput} setSearchInput={setSearchInput} />
             <MovieList movies = {movies} handleFavourites = {handleFavourites} 
             setFavouriteMovies = {setFavouriteMovies}/>
              

        </>
    )
}

export default Home;

Favourites.js

import React from "react"

const Favourites = () => {

    return ( 
        <>
            <h1>Favourites</h1>
            
        </>
    )
}

export default Favourites;

CodePudding user response:

Unless you are using an API or back-end in order to store the favorites, this would be not possible if you are solely relying on the state.

Since component states gets cleared as soon as it is unmounted.

If your application is purely front-end and you are okay storing the data within the user's browser, I would suggest utilizing localStorage

CodePudding user response:

I recommend you to push favorites movies to localStorage. By doing so, you can use that data on favorite page and when user close browser and come back again, he will still have his chosen movies saved.

Using context will also allow you to pass data trough components but it will be cleared after user leaves site.

CodePudding user response:

If you use Link or history to switch to another route, you can pass a state that is not visible in the URL but accessible from the destination route.

In your Home.js you could add for instance a button like this:

const history = useHistory();
...

// Within returned tree, add a button:

<button onClick={() => {history.push('/favourites', {movies: favouriteMovies});}}>
  Go to favourites
</button>

// or simply a link (don't need history in this case):

<Link to={{pathname: "/favourites", state: {movies: favouriteMovies}}}>
  Go to favourites
</Link>

Then, in Favourites.js, access your state by:

const {state} = useLocation();
const movies = state.movies;
  • Related