简体   繁体   中英

React Context value disappears when reloading page

I successfully fetch data of a movie inside useEffect(). However, when the page is reloaded, the value const { selectedMovie } = useContext(MoviesContext) disappears and 404 errors are printed out in the console (since the default value 0 is being used and incorrect called to API is being done).

This is the component that is reloaded:

import {useState, useEffect, useContext} from "react";
import Topbar from '../Header/Topbar';
import { fetchSelectedMovie } from "../../services/movies.service";
import {Grid, Card, CardMedia} from '@material-ui/core';
import noImage from '../../images/no-image-available.png';
import { MoviesContext } from "../../services/context";
import './Pages.css';
const posterBaseUrl = "https://image.tmdb.org/t/p/w300";
interface Genre {
  id: number;
  name: string;
}
interface Movie {
  id: number;
  title: string;
  vote_average: number;
  overview: string;
  poster_path?: string;
  release_date: string;
  budget: number;
  revenue: number;
  genres: Genre[];
}

const MoviePage = (props: any) => {

  const { selectedMovie } = useContext(MoviesContext);

  const [movie, setMovie] = useState<Movie>(
    {
      id: 0,
      title: '',
      vote_average: 0,
      overview: '',
      poster_path: noImage,
      release_date: '',
      budget: 0,
      revenue: 0,
      genres: [],
    }
  );
  const [movieImg, setMovieImg] = useState<string>(noImage);

  useEffect(() => {
    const callAPI = async () => {
      const fetchedMovieInfo = await fetchSelectedMovie(Number(selectedMovie));
      setMovie(fetchedMovieInfo);
      setMovieImg(posterBaseUrl+fetchedMovieInfo.poster_path);
    }

    callAPI();
  }, [selectedMovie]);

  return (
    <>
      <Topbar></Topbar>
      <Grid container spacing={2} className="container-movie-page">
        <Grid item xs={6} sm={3}>
          <Card className="card">
            <CardMedia
              component="img"
              alt={"Poster of " + movie.title}
              image={movieImg}
              title={movie.title}
            />
          </Card>
        </Grid>
        <Grid item xs={6} sm={9} className="align-left">
          <h1 className="title">
            {movie.title}
          </h1>
        </Grid>
    </>
  );
}

export default MoviePage;

React Context that is used:

import React from "react";
import { Movie } from "./movies.service";

export const MoviesContext = React.createContext<{
    movies: Movie[];
    updateMovies: Function;
    selectedMovie: number;
    setSelectedMovie: (value: number) => void;
  }>({
    movies: [],
    updateMovies: Function,
    selectedMovie: 0,
    setSelectedMovie: () => {},
  });

These are 404 errors I receive:

在此处输入图片说明

What changes should be made?

Indeed, State is lost with React when you Refresh the page as it is no persistent.

You should use another method to keep this information even if the user refresh the page. Here are the options:

  • In the database. Could work if the user is behind an authentification (Login password). Example User name: Paul , id; 3131 id; 3131 , did click on the button "connect". In your database, you add a column in the table User called userConnect = true
  • In the url. As soon as the user click on the button "connect" you change the URL with React router . For example the URL was mydomain.com , and after clicking it becomes mydomain.com?clicked=true . If the user refresh your page, you still have the information about the user who clicked on the button.
  • In a cookie (More info here https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies )
  • In local Storage (More info here https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/local )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM