A
A
Anastasia2020-12-02 15:00:56
React
Anastasia, 2020-12-02 15:00:56

How to change the state correctly so that the previous one comes?

I know that it is correct to change the state of the previous state, that is, setState( prev => !prev ), but how to write it for my case, when the previous state should change to item.value ?
perhaps that's why I catch a bug - in the picture - I press the D button after the M button and the value of the M button is saved in the indicator, then if you press D several times, the desired value is saved

5fc7819bad089148717394.jpeg

export const ControlIndicators = ({ position }) => {
  const [indicator, setIndicator] = useState('month');
  
  const clickHandler = value => {
    setIndicator(value);
    console.log('indicator: ', indicator);
  };

  const buttons = [
    { title: 'Дневной показатель', value: 'day' },
    { title: 'Месячный показатель', value: 'month' },
  ];

  return (
    <Control position={position} className="leaflet-bar leaflet-bar-row">
      {buttons.map(item => {
        return (
          <button
            className={
              indicator === item.value ? 'buttons-leaflet-item active' : 'buttons-leaflet-item'
            }
            title={item.title}
            value={item.value}
            onClick={() => clickHandler(item.value)}
          >
            {item.value === 'day' ? 'Д' : 'М'}
          </button>
        );
      })}
    </Control>
  );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-12-02
@0xD34F

I press the D button after the M button and the value of the M button is saved in the indicator

Nonsense. Where did you get it from? The value you save is in value, you don't need to look at the indicator at the time of calling setIndicator. Do it through an effect:
useEffect(() => console.log('indicator: ', indicator), [ indicator ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question