Home > other >  Losing Context Data on Page Refresh
Losing Context Data on Page Refresh

Time:08-26

I have a component that displays recipe data from an API, when the user clicks the button I am sending the recipe item ID up to Context with a recipeCtx.addRecipeID(id). this button click also navigates the user to a page to display the recipe info.

const RecipeGridItem = ({title, image, id}) => {
  const recipeCtx = useContext(RecipeContext);
  const history = useHistory();

  const recipeInfoSend = () => {
    recipeCtx.addRecipeID(id);
    history.push(`/info/${title.replace(/ /g,"-")}`);
  }
  
  return (
    <div className={classes['grid-item']}>
      <div className={classes['grid-item-inner']}>
        <div className={classes['grid-front']}>
        <img src={image} alt="" />
        <h3>{title}</h3>
        </div>
        <div className={classes['grid-back']}>
          {/* <p>{summary}</p> */}
          <Button onClick={recipeInfoSend} btnText={'More Info'}/>
        </div>
      </div>
    </div>
  )
}

export default RecipeGridItem;

I then save the id state in my context provider

const [recipeId, setRecipeId] = useState('');
const addRecipeIDHandler = (id) => {
    setRecipeId(id);
  }

const recipeProviderValue = {
      recipeId: recipeId,
    };

Then I call the recipe ID down from context in my RecipeInfoPage.js file to make the necessary API call, this is the page the user is navigated to after clicking the button.

The data displays on the first page load, but if I refresh the page, the id value seems to get lost and all of my data from the api request is gone, leaving me with a blank page

import React, {useState, useContext, useEffect} from 'react';
import Container from '../Layout/Container';
import RecipeContext from '../../store/recipe-context';

const RecipeInfoPage = () => {
  const recipeCtx = useContext(RecipeContext);
  const recipeId = recipeCtx.recipeId;
  const [recipeInfo, setRecipeInfo] = useState({});

  const getRecipeInfo = () => {
    fetch(`https://api.spoonacular.com/recipes/${recipeId}/information?apiKey=${process.env.REACT_APP_API_KEY}`)
    .then(res => res.json())
    .then(data => setRecipeInfo(data));
  }
    //Grid Recipes
    useEffect(() => {
      getRecipeInfo();
    }, [recipeId]);

    

  return (
    <Container>
      <h1>{recipeInfo.title}</h1>
      <p dangerouslySetInnerHTML={{__html: recipeInfo.summary }}></p>
      
    </Container>
  )
}

export default RecipeInfoPage;

CodePudding user response:

I am not very sure about this but isn't the command something along the lines of localStorage['myKey'] = 'somestring'; // only strings

CodePudding user response:

You should use params or query string instead of managing the id yourself.

history.push(`/info/${recipeId}`);

You will need to handle that route:

<Route path={'/info/:recipeId'}>
  <YourComponent />
</Route>

And in YourComponent you can get the recipeId with useParams hook.
And you can fetch the data with recipeId in useEffect

  • Related