0

Previously everything was working fine when my input was int/ numbers only but I tried to change input type to float. That's when things starts getting weird.

React itself will run up to 2x for my inputs before showing error.

The below is my component page:

    import React from 'react';
import Select from "react-select";
import { useForm, Controller } from "react-hook-form";
import TextField from '@mui/material/TextField';
import Input from '@mui/material/Input';
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import AddIcon from '@mui/icons-material/Add';

//redux
import { useSelector, useDispatch } from 'react-redux';
import {
    addproduct,
    removeproduct,
    selectproducts,
    selectproductsTotal,
} from '../features/sales/sales.slice';


const PdtListItem = (props) => {
    const _removeproduct = () => {
        props.trigger(props.id)
    }
    return (
        <Grid container spacing={1} direction="row" justifyContent="center" alignItems="center" className="pdtListItem" id={props.id}>
            <Grid item sm={4} xs={6}><Typography>{props.productdesc}</Typography></Grid>
            <Grid item sm={2} xs={2}><Typography>#{props.quantity}</Typography></Grid>
            <Grid item sm={2} xs={2}><Typography>${props.price}</Typography></Grid>
            <Grid item sm={2} xs={2}><Typography>${props.subtotal}</Typography></Grid>
            <Button color="error" variant="outlined" size="medium" onClick={_removeproduct}>❌</Button>
        </Grid>
    )
};

const Sales = () => {
    const dispatch = useDispatch();
    const productselector = useSelector(selectproducts);
    const producttotalselector = useSelector(selectproductsTotal);
    const { control, handleSubmit, reset } = useForm({
        defaultValues: {
            quantity: "",
            price: "",
            productlist: null
        }
    });


    React.useEffect(() => {
        reset()
    }, [productselector, producttotalselector])

    const onSubmit = data => {
        let pricefloat = parseFloat(data.price).toFixed(2)
        let quantityfloat = parseFloat(data.quantity).toFixed(1)
        let subtotalfloat = parseFloat(pricefloat * quantityfloat).toFixed(2)
        let _data = {
            price: pricefloat,
            quantity: quantityfloat,
            productdesc: data.productdesc.value,
            subtotal: subtotalfloat
        }
        dispatch(addproduct(_data));
    };

    const removehandle = (id) => {
        dispatch(removeproduct(id));
    }

    return (
        <div>
            <Paper sx={{
                p: 2,
                margin: 'auto',
                maxWidth: 600,
                flexGrow: 1,
                backgroundColor: (theme) =>
                    theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
            }}
            >
                <Grid container spacing={1} direction="row" justifyContent="center" alignItems="center">
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <Grid item >

                            <Controller
                                name="productdesc"
                                control={control}
                                render={({ field }) => <Select
                                    isSearchable
                                    {...field}
                                    options={[
                                        { value: "product1", label: "product1" },
                                        { value: "product2", label: "product2" },
                                        { value: "product3", label: "product3" }
                                    ]}
                                />}
                            />
                        </Grid>
                        <Grid container spacing={1} direction="row" justifyContent="space-evenly" alignItems="center">
                            <Grid item sm={3} xs={12}>
                                <Controller
                                    name="quantity"
                                    control={control}
                                    render={({ field }) => (
                                        <Input
                                            {...field}
                                            required
                                            placeholder='#'
                                            autoComplete='off'
                                            variant='standard'
                                            label='quantity'
                                            type='number'
                                            inputProps={{
                                                maxLength: 13,
                                                step: "0.1"
                                              }}
                                        />)}
                                />
                            </Grid>
                            <Grid item sm={3} xs={6}>

                                <Controller
                                    name="price"
                                    control={control}
                                    render={({ field }) => (
                                        <Input
                                            {...field}
                                            required
                                            placeholder='$'
                                            autoComplete='off'
                                            variant='standard'
                                            label='price'
                                            type='number'
                                            inputProps={{
                                                maxLength: 13,
                                                step: "0.01"
                                              }}
                                        />)}
                                />
                            </Grid>
                            <Grid item sm={3} xs={6} >
                                <Button type="submit" variant="outlined" size="small"><AddIcon /></Button>
                            </Grid>
                        </Grid>
                    </form>
                </Grid>
                        <Box sx={{pt:3}}>
                        <Grid container justifyContent="right" alignItems="right">
                            <Grid item>
                            <Typography>Subtotal (Exclude Tax): {producttotalselector}</Typography>
                            </Grid>
                        </Grid>
                        </Box>


                
                <div>
                    {productselector.map((pdtitem) =>
                        <PdtListItem
                            key={pdtitem.id}
                            id={pdtitem.id}
                            price={pdtitem.price}
                            quantity={pdtitem.quantity}
                            productdesc={pdtitem.productdesc}
                            subtotal={pdtitem.subtotal}
                            trigger={removehandle}
                        />
                    )}
                </div>
            </Paper>
        </div>
    );
};

export default Sales;

This is my slice that is connected to the above component

import { createSlice, nanoid } from '@reduxjs/toolkit';
import _ from 'lodash';


const initialState = []


const salesSlice = createSlice({
  name: 'sales',
  initialState,
  // The `reducers` field lets us define reducers and generate associated actions
  reducers: {

    addproduct : (state, action) => {
      
      const products = {
        id: nanoid(),
        price: action.payload.price,
        quantity: action.payload.quantity,
        productdesc: action.payload.productdesc,
        subtotal: action.payload.subtotal
      }
        return (
            [...state, products]
        )
    },

    removeproduct: (state, action) => {
      return (
        state = state.filter((arrow) => arrow.id !== action.payload)
      )
    }

  }
});

export const { addproduct, removeproduct } = salesSlice.actions;

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`
export const selectproducts = (state) => state.sales;
export const selectproductsTotal = ((state) =>  {
  let _subtotal = _.map(state.sales, "subtotal")
  return (
    
    _subtotal.reduce((a,b) => parseFloat(a)+parseFloat(b),0.00)
  )
})

export default salesSlice.reducer;

So when i tried to run they will give me the below error..

sale.component.js:62 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'value')
    at onSubmit (sale.component.js:62:1)
    at createFormControl.ts:1042:1
onSubmit    @   sale.component.js:62
(anonymous) @   createFormControl.ts:1042
await in (anonymous) (async)        
callCallback    @   react-dom.development.js:4157
invokeGuardedCallbackDev    @   react-dom.development.js:4206
invokeGuardedCallback   @   react-dom.development.js:4270
invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:4284
executeDispatch @   react-dom.development.js:9011
processDispatchQueueItemsInOrder    @   react-dom.development.js:9043
processDispatchQueue    @   react-dom.development.js:9056
dispatchEventsForPlugins    @   react-dom.development.js:9067
(anonymous) @   react-dom.development.js:9258
batchedUpdates$1    @   react-dom.development.js:25979
batchedUpdates  @   react-dom.development.js:3984
dispatchEventForPluginEventSystem   @   react-dom.development.js:9257
dispatchEvent   @   react-dom.development.js:6435
dispatchDiscreteEvent   @   react-dom.development.js:6410

So I'm just trying to fix this issue, but I am not sure where is the problem, is it with redux tookkit or mui or maybe I should take note of something. Kindly assist & advice?

I am currently running react 18.0 & latest redux tookit

boyboi
  • 11
  • 1
  • 3

1 Answers1

0

Sorry for every1's time.

After I went thru the log, I realize the problem is not with redux/ rtk or react or mui.

react-select was the problem..

boyboi
  • 11
  • 1
  • 3