Home > Back-end >  React component is not re-rendering on state change
React component is not re-rendering on state change

Time:12-31

I am dispatching an object to an array and I get an information that it was sended successfully but length of this array hasn't changed in my Header component. There

store.getState().Basket.length

is not re-rendering. The value only re-renders when I change the path.

This is Header component:

function Header() {
  return (
    <div id="Header">
      <Link to='/' style={{ display: 'flex',textDecoration: 'none', color: '#000' }}>
        <div className='Header_Pole'>
          <img src={logo} alt='Logo' className='Header_Pole_img'/>   
        </div>
      </Link>
      <Link to='/basket' style={{ display: 'flex',textDecoration: 'none', color: '#000' }}>
        <div className='Header_Pole'>
          <img src={shoppingBasketIcon} alt='Basket' className='Header_Pole_img'/> 
          <p className='itemsCounter'>{ store.getState().Basket.length }</p>
        </div>
      </Link>
    </div>
  )
}

export default Header;

store:

export const store = configureStore({
    reducer: {
        Basket: basketReducer
    }
  })

dispatch function:

const addToBasket = () => {
    dispatch({
      type: addtoBASKET,
      item: {
      id: Products[idOfProduct - 1].id,
      name:Products[idOfProduct - 1].name,
      type: Products[idOfProduct - 1].type,
      image: Products[idOfProduct - 1].image,
      price:Products[idOfProduct - 1].price,
      size: gettingSize() // return a size
      }
    })
  }

I tried to find some stuff on the internet but nothing worked.

CodePudding user response:

You should use the hook useSelector from react-redux
useSelector will notify your component when the redux state change and update your component

import { useSelector } from 'react-redux'

function Header() {
  const basketLength = useSelector((state)=>state.Basket.length)
  return (
    <div id="Header">
       // [...]
       <p className='itemsCounter'>{basketLength}</p>
    </div>
  )
}

export default Header;

CodePudding user response:

You have to use react-redux to work with redux state in react. Otherwise you'd have to implement state synchronization between the two manually.

  • Related