0

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>
  )
}

3 Answers 3

2

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

const stateVideos = [...videos];
Sign up to request clarification or add additional context in comments.

Comments

0

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(...);
}

Comments

0

Redux data is immutable as explained here

When you did this:

const {videos} = useSelector((state)=>state.videos);

and then on the child component you did this:

const sorted = state.sort((a,b)=>(a.clicked < b.clicked) ? 1 : -1);

where state is actually the reference to videos

By sorting the redux data you are mutating it (sort does sorting inline), therefore the solution for this is cloning the data like this:

const stateVideos = [...videos];

or in the child component you can do something like this:

const sorted = state.slice().sort((a,b)=>(a.clicked < b.clicked) ? 1 : -1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.