I am importing an array into "restMovies" and it's working fine - all the data is in place in "restmovies" and is delievered to the rest of the app via the context provider.
However, I need to make changes in the array so I'm trying to copy the "restMovies" array to the "movies" array that will be the array that's being delievered to the rest of the app.
But for some reason I can't "setMovies", the movies array stays empty.
Help?
export const MoviesContext = createContext();
export const MoviesContextProvider = (props) =>
{
const [restMovies, setRestMovies] = useState([]);
const [movies, setMovies] = useState([])
useEffect(() =>
{
axios.get("https://api.tvmaze.com/shows").then(resp => setRestMovies(resp.data));
}, [restMovies.values])
useEffect(() =>
{
restMovies.map(item =>
{
setMovies([...movies, item])
})
}, [movies.values, restMovies.values])
return (
<MoviesContext.Provider value = {[movies]}>
{props.children}
</MoviesContext.Provider>)
}
Issue
movies.values
, andrestMovies.values
are undefined always, so the dependency values never change and the effect callback is never re-triggered (from the initial triggering when mounted). Mapping arrays is also for returning new arrays, not side-effects like pushing into other arrays, etc...Solution
Run the second effect with only
restMovies
array as a dependency (don't cause infinite looping), and use a functional state update to correctly spread (copy) currentmovies
andrestMovies
state arrays into a new array reference. I assume you likely also only wanted the first effect to run once when the component mounts in order to do the data fetch, so remove all dependencies for the first effect.