Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data is not being passed correctly via props React

Tell me please

Why the data passed through props does not change when it is changed in useLocation()

  1. I have data transfer via Link

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    <Link
      to={{
      pathname: '/catalog/product_card/' + product.id,
      state: { product }
    }}>
      <span className="product-name">{product.name}</span>
    </Link>
    
  2. I get them via useLocation in ProductCardView

    const CategoryViewDesktop = ({productState}:any) => {
      const product = productState.product;
    
      console.log(product)
      return (
        <div>{product.id}</div>
      )
    }
    
    const ProductCardView = () => {
      const { state } = useLocation()
      const productState = {products: state.products, product: state.product}
    
      console.log(state.product)
      return (
        <Page page="catalog.products">
            <CategoryViewDesktop productState={productState} />
        </Page>
      )
    }
    
  3. In ProductCardView – data changes when interacting with Link, but the same data comes to ProductCardInfo

Why is this and how to fix it?

>Solution :

Because your variable productState is not reactive, you can use hook useState or use useLocation state directly on child component props .

  const CategoryViewDesktop = ({productState}:any) => {
        const product = productState.product;
        
        console.log(product)
        return (
            <div>{product.id}</div>
        )
    }
    
    const ProductCardView = () => {
        const { state } = useLocation()
    
        console.log(state.product)
        return (
            <Page page="catalog.products">
                <CategoryViewDesktop productState={state} />
            </Page>
        )
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading