Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to call the action creator add Product from the form Product component. I am not getting where I am going wrong. Can someone please help me out to solve this? I am new to redux so how can I achieve the solution so that when the form is filled the product should be added and the action creator gets called.

Here's the code :


FormProduct.js

import { makeStyles, TextField, Grid } from '@material-ui/core'
import React, { useState, useEffect } from 'react'
import { useForm, Form } from '../useForm'
import Input from '../../components/controls/Input'
import Select from '../controls/Select'
import * as productService from '../../services/productService'
import DatePicker from '../controls/DatePicker'
import Button from '../controls/Button'

const initialValues = {
    id: 0,
    name: '',
    description: '',
    quantity: '',
    price: '',
    dop: new Date(),
    category: ''
}

const FormProduct = (props) => {
    const validate = (fieldValues = values) => {
        let errors = { }
        if ('name' in fieldValues)
            errors.name = values.name ? '' : 'This field is required'
        if ('description' in fieldValues)
            errors.description = values.description ? '' : 'This field is required'
        if ('quantity' in fieldValues)
            errors.quantity = values.quantity ? '' : 'This field is required'
        if ('price' in fieldValues)
            errors.price = values.price ? '' : 'This field is required'
        if ('category' in fieldValues)
            errors.category = values.category.length != 0 ? '' : 'This field is required'
        setErrors({
            ...errors
        })
        if (fieldValues == values)
            return Object.values(errors).every((formValues) => formValues == '')
    }
    const { values, setValues, handleChange, errors, setErrors, resetForm } = useForm(initialValues, true, validate)

    const handleSubmit = (e) => {
        console.log('handleSubmit',props)
        e.preventDefault()
        if (validate())
        {
            props.onSubmit(values)
        }
    }
    return (
        <Form onSubmit={handleSubmit}>
            <Grid container>
                <Grid item>
                    <Input
                        name='name'
                        value={values.name}
                        label='Name'
                        onChange={handleChange}
                        error={errors.name} />
                    <Input
                        label='Description'
                        name='description'
                        value={values.description}
                        onChange={handleChange}
                        error={errors.description} />
                    <Input
                        label='Quantity'
                        name='quantity'
                        value={values.quantity}
                        onChange={handleChange}
                        error={errors.quantity} />
                    <Input
                        label='Price'
                        name='price'
                        value={values.price}
                        onChange={handleChange}
                        error={errors.price} />
                    <DatePicker
                        name='dop'
                        label='Date Of Purchase'
                        value={values.dop}
                        onChange={handleChange} />
                    <Select
                        name='category'
                        label='Category'
                        value={values.category}
                        onChange={handleChange}
                        options={productService.getProductCollection()}
                        error={errors.category} />
                    <div>
                        <Button variant='contained'
                            color='primary'
                            size='large'
                            text='Submit'
                            type='submit' />
                    </div>
                </Grid>
            </Grid>
        </Form>
    )
}

export default FormProduct

AddProduct.js

import React from 'react'
import {connect} from 'react-redux'
import {addProduct} from 'redux'
import FormProduct from './FormProduct'

const AddProduct = (props) => {
    const onSubmit=(product)=>{
        props.addProduct(product)
    }
    return (
        <div>
            <FormProduct onSubmit={onSubmit}/>
        </div>
    )
}

export default connect(null,{addProduct:addProduct})(AddProduct)

actions.js

import products from '../apis/products'
import {ADD_PRODUCT,LIST_ALL_PRODUCTS} from './types'
import { v4 as uuid } from 'uuid'

export const addProduct=(productDetails)=>{
    return async (dispatch)=>{
        const productId=uuid()
        const response=await products.post('/products',{...productDetails,productId})
        dispatch({
            type:ADD_PRODUCT,
            payload:response.data
        })
    }
}

reducers.js

import {ADD_PRODUCT} from '../actions/types'
import _ from 'lodash'

const productsReducer=(state={},action)=>{
    switch(action.type){
        case ADD_PRODUCT:
            return {...state,[action.payload.id]:action.payload}
        default:
            return state
    }
}

export default productsReducer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
585 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is not a redux error, since onSubmit is a normal react prop you are passing in manually. Something might be going wrong there, but from these snippets it is not obvious what. But nothing redux-related.

Some words to your redux usage though: if you are learning redux right now, you are following an outdated source. Redux has changed siginificantly on the past two years. If you follow the official recommendations, modern redux will not contain

  • use of connect for function components (instead, use useDispatch and useSelector)
  • hand-written string action types
  • hand-written actions or action creators
  • use of switch...case or immutable logic in reducers

Please, drop whatever tutorial you are following and follow the official redux tutorials instead. You will be writing probably only 1/3 of the code you are writing right now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...