famo
famo

Reputation: 180

react/redux app - issue when getting actions from redux slice to react component

Hi I am creating a react app using reduxtoolkit it has addto cart function I am trying to update the add to cart button using redux state, when I am getting redux actions for increment and decrement its showing an error ReferenceError: Cannot access 'selectadto' before initialization not sure what I am missing here, if anyone knows please do check

my component is below


import React, { useState, useEffect } from "react";

import { useDispatch, useSelector } from "react-redux";
import { selectAddSlice } from "./features/auth/addsSlice";
import { selectadto } from "./features/auth/addtoSlice";
import { increment, decriment } from "./features/auth/addtoSlice";

const Addtocart = (props) => {
  const dispatch = useDispatch();
  const selectedAdds = useSelector(selectAddSlice);
  const selectedTodo = useSelector(selectadto);

  useEffect(() => {
    console.log(selectedTodo);
  }, [selectedTodo]);
  const onIncrementclicked = (e) => {
    e.preventDefault();
    dispatch(increment());
  };
  const onDecrimentclicked = (e) => {
    e.preventDefault();
    dispatch(decriment());
  };
  return (
    <div>
      {selectedAdds.map((add) => (
        <div key={add.id}>
          <div> {add.addname}</div>
          <div> {add.price}</div>
          <button onClick={onIncrementclicked()}>{selectedTodo}</button>
          <button onClick={onDecrimentclicked()}>{selectedTodo}</button>
        </div>
      ))}
    </div>
  );
};

export default Addtocart;

my redux slices is below

import { createSlice } from '@reduxjs/toolkit';


export const addtoSlice = createSlice({
    name: 'addto',
    initialState: {
        currentamount: 0
    },
    reducers: {
        increment: state => {
            state.curentamount++
        },
        decriment: state => {
            state.currentamount--
        },
    },
});

export const { increment, decriment } = addtoSlice.actions;

export const selectadto = state => state.addto.currentamount;

export default addtoSlice.reducer;

the error message is below


  TypeError: Cannot read property 'preventDefault' of undefined
onIncrementclicked
src/Addtocart.js:17
  14 |   console.log(selectedTodo);
  15 | }, [selectedTodo]);
  16 | const onIncrementclicked = (e) => {
> 17 |   e.preventDefault();
     | ^  18 |   dispatch(increment());
  19 | };
  20 | const onDecrimentclicked = (e) => {

Upvotes: 0

Views: 563

Answers (1)

phry
phry

Reputation: 44078

In const selectadto = useSelector(selectadto); you declare a new variable called selectadto while using a reducer named selectadto. You should probably give one of the two a different name.

Upvotes: 1

Related Questions