Skip to content
Advertisement

Save a prop when moving away and coming back to page ReactJS

I have a username property that I have passed on from “log in” route to “product list” route using

return <Redirect to={{
    pathname: "/products",
    state: username
  }}/>  

I then have a <Link to={'/products/${product.id}'}>More info</Link> that sends me from “product list” to an “individual product”.

When I then come back to the “product list” <Link to={'/products'}>Back</Link>, the username is gone. Is there a way to keep the username, so when the user is logged in and moves back and forth between routes, it keeps being stored?

Here is the full code for my “product list” route where I want the username to be stored:

import React, {useState, useEffect} from 'react';
import './Products.css';
import {Link} from 'react-router-dom';

function Products(props) {

  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchProducts = async () => {

      const data = await fetch("https://example.com/products");
  
      const products = await data.json();
      console.log(products);
      setProducts(products);
    };
    fetchProducts();
  }, []);

  let username = props.location.state;

  return (   
    <div> 
      <p className = "HelloUser">Hello, {username}</p>
      <p className = "ProductTitle">Our Selection</p>
      <div className = "ProductGrid">
        {products.map(product =>(
        <div className = "ProductBox" key={product.id}>
          <img className ="ProductImage" src={product.image} alt="did not load"/>
          <p className ="ProductName">{product.name}</p>
          <p className ="ProductDiscountedPrice">{"£" + (Math.round(product.discountedPrice * 100) / 100).toFixed(2)}</p>
          <p className ="ProductPrice">{"£" + (Math.round(product.price * 100) / 100).toFixed(2)}</p>
          <Link to={`/products/${product.id}`} className="MoreInfoButton">More info</Link>
        </div>
        ))}
      </div>
    </div>
  )
}

export default Products;

Advertisement

Answer

SOLVED: Solved it by passing on the username prop further to the “individual product” component. That way when I hit back to the “product list”, the username stays.

Or even better storing Username in the sessionStorage.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement