Redux-toolkit, React - Cannot assign to read only property '0' of object

Viewed 196

I have found no answer, which brought a solution. The error is thrown in the const sorted of my child component. I tried to give the destructured array "videos" into an extra const, but that not works. Thanks for your help

Here is the snippet from my child-component:

const VideoSlider = ({state}) => {
    const sorted = state.sort((a,b)=>(a.clicked < b.clicked) ? 1 : -1);
    const [slideIndex, setSlideIndex] = useState(0);
    const handleClick = (direction)=>{
       if(direction === "left"){
           setSlideIndex(slideIndex > 0 ? slideIndex-1 : 0);
       }
       else{
           setSlideIndex(slideIndex < sorted.length - 4 ? slideIndex + 1 : sorted.length - 4);
       }
    }

Here is the snippet from my parent component:

const MostSeen = () => {
const {videos} = useSelector((state)=>state.videos);
const dispatch = useDispatch();
useEffect(()=>{
    dispatch(getAllVideos());
}, [dispatch]);
const stateVideos = videos;
  return (
    <Container>
        <TitleHolder>
            <Title>Most viewed videos</Title>
        </TitleHolder>
        <ContentHolder>
            <VideoSlider state={stateVideos}/>
        </ContentHolder>
    </Container>
  )
}
2 Answers

I have found the solution by myself. It must be:

const stateVideos = [...videos];

Apparently assigning a redux state to a var (or const) like

const reduxData = useSelector(state => state.user.data);

or

const reduxData = useSelector(state => state.user.data);
const newConst = reduxData;

quite literally assigns the entire state to the var (or const). So when we try to sort and assign new data to the var (or const), we get the above error since we need to use dispatch to update a redux state. However using the spread operator we can just assign the value of the state to a var (or const).

const FlightSummary = () => {
  const reduxData = useSelector(state => state.user.data);
  var useableData = [...reduxData];
  useableData.sort((a, b) => {
    return a.date < b.date;
  });

  return(...);
}
Related