skip to Main Content

enter image description hereI have an interesting problem. I have a product page and an ‘add item’ button. When the button is clicked the product id will be updated in the ‘items’ array state variable. I’m getting the product id from the url params using ‘useParams’ hook.

Now here’s the thing. I put log statements at different steps in my code and found that when I navigate FROM the home page TO the product page, the page url param i.e., product id is correctly getting stored and logged.

But when I click the ‘add item’ button, it seems to immediately re-render the page and then sets the url param from the useParams hook – which was previously holding the proper page id – as ‘undefined’, which then is subsequently updating to the ‘items’ state variable as ‘undefined’.

Here’s the code:

import { useParams, Link } from "react-router-dom";
import { useState } from 'react';


function AddToCart() {
  const [items, setItems] = useState([]);
  const { id } = useParams();
  console.log(id);

  function addItem() {
    setItems([...items, id]);
  }

  console.log(items);

    return ( 
        <div className='add-to-cart'>
          <button className='add-btn' onClick={() => addItem()}>Add Item</button>
          {/* <Link to={`cart/${items}`}><FontAwesomeIcon className='cart-btn' icon={faBasketShopping} size='3x' /></Link> */}
        </div>
    );
}

export default AddToCart;

Page route:

 function App() {
  return (
    <div className="App">
      <Header/>
      <MenuTitle/>
        <Routes>
          <Route path='/' element={<Home/>}/>
          <Route path='/item_page/:id' element={<Item/>}/>
          {/* <Route path='/cart/:id' element={<Cart/>}/> */}
        </Routes>
      <AddToCart/>
    </div>
  );
}

export default App;

I looked up on Google and tried the e.preventDefault() method inside the function block but that didn’t work either. How can I solve this?

Adding screen snips of console before and after clicking the button

2

Answers


  1. Chosen as BEST ANSWER

    So I found out that I was rendering this AddToCart component in two different places mistakenly. One in the App.js file with the intention to make it render on all pages. The other on the product page which is actually holding the context of the current page route. Removed the former duplicate from the App.js which leaves us with the actual button and it is now working as expected.enter image description here


  2. error cause

    setState is an asynchronous processing function.

    So when you print items to the console, the state that has not been updated yet is printed to the console. That seems to be the cause.

    error resolution

    Let’s handle asynchronous processing using useEffect.

      useEffect(() => {
        console.log('Updated items:', items);
      }, [items]);
    
      function addItem() {
        setItems(prevItems => [...prevItems, id]);
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search