Не работает useSelector, когда dispatch в useEffect
Пытаюсь сохранить координаты в store, при отрисовке компонента с помощью кода:
useEffect(() => {
if (ref.current) {
const top = ref.current.getBoundingClientRect().top;
dispatch(setCoordinate([{ top: top - 30, left: ref.current.offsetWidth - 50 - 64 }]))
}
})
Почему-то переменная coordinate при этом не обновляется
function Client(props: IClient) {
const coordinate = useAppSelector((state) => state.areaCoordinateReducer);
const startTouch = () => {
console.log(coordinate);
}
return (<> <div className="client" onTouchStart={startTouch}></div> </>)
В чем может быть проблема? Или может есть идеи как можно по-другому сохранить координаты не связанного компонента?
Код reducer:
export const coordinateSlice = createSlice({
name: 'areaCoordinate',
initialState,
reducers: {
setCoordinate(state, action: PayloadAction<IAreaCoordinate[]>) {
console.log(state);
state = [...action.payload];
console.log(state);
},
},
});
Ответы (1 шт):
Автор решения: Kalinina Oksana
→ Ссылка
Ошибка была в reducer Неправильно записывала новое значение в state
export const coordinateSlice = createSlice({
name: 'areaCoordinate',
initialState,
reducers: {
setCoordinate(state, action: PayloadAction<IAreaCoordinate[]>) {
state.arr = [...action.payload];
},
},
});