Home > Mobile >  Make an update request using Axios in React and Material UI
Make an update request using Axios in React and Material UI

Time:11-17

I am pretty new to React, and the only CRUD functionality I have do was in MVC .net, so I am pretty lost here and none of the tutorials I am finding seem to be the situation I have going on...or maybe I am just misunderstanding them. The tips I got with my initial question helped, but I am still no getting it to work, so hopefully now I have supplies enough info to help other help me. I did no include all of the input fields because their are like 15 and it was just redundant.

Also, my input TextField keeps giving me a console error about being uncontrolled:

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen

I have tried everything have seen online (defaultValue='') and can't seem to control the fields.

As for my main concert....

I am pulling up the modal using this onClick event:

onClick={()=> {handleEditModal(item)}}

modalFunctions.js

// Modal Functionality
export function ModalFunctions() {
    const [selectedRecord, setSelectedRecord] = useState([]);
    const [openModal, setOpenModal] = useState(false);

    const handleEditModal = item =>{
        setOpenModal(true)
        setSelectedRecord(item)
    } 

    return {
        selectedRecord,
        setSelectedRecord,
        openModal,
        setOpenModal,
        handleEditModal,
        handleDetailModal
    }
}

// Form Functionality
export function FormFunctions(validateOnChange = false, validate) {
    const [values, setValues] = useState('');
    const [errors, setErrors] = useState({});
  
    const handleInputChange = e => {
        const { name, value } = e.target
        setValues({
            ...values,
            [name]: value
        })
        if (validateOnChange)
            validate({ [name]: value })
    }
    return {errors, handleInputChange, setErrors, setValues, values}
}

DataTable.js

// Imported Modal Functions
    const {
        selectedRecord,
        openModal,
        setOpenModal,
        handleEditModal,
        handleDetailModal
        } = ModalFunctions();

// Fetch Data
useEffect(() => {
    const fetchData = async () => {
        setLoading(true);
        try {
        const {data: response} = await axios.get('http://----/api/tanks');
        setTableData(response);
        } catch (error) {
        console.error(error.message);
        }
        setLoading(false);
  }
  fetchData();
}, [setTableData, setLoading]);


// The Modal
  return(
        <Modal
                title={ "Editing: "   (selectedRecord.tankName) }
                openModal={openModal}
                setOpenModal={setOpenModal}
            >
                    <TankEdit
                        selectedRecord={selectedRecord}
                        setOpenModal={setOpenModal}
                        openModal={openModal} 
                    />
            </Modal>
    )

TankEdit.js

export function TankEdit(props) {
    const { selectedRecord, setSelectedRecord, openModal, setOpenModal } = props;

    const validate = (fieldValues = item) => {
        let temp = { ...errors }
        if ('tankName' in fieldValues)
            temp.tankName = fieldValues.tankName ? "" : "This field is required."
        setErrors({
            ...temp
        })
        if (fieldValues === values)
            return Object.values(temp).every(x => x === " ")
    }

    const {
        values,
        setValues,
        errors,
        setErrors,
        handleInputChange,
    } = FormFunctions(true, validate);

    useEffect(() => {
        if (selectedRecord !== null)
            setValues({
                ...selectedRecord
        })
    }, [selectedRecord, setValues])

    
    const editRecord = async () => {
        const {data: response} = await axios.put('http://----/api/tanks');
        setSelectedRecord(null)
        setOpenModal(false)
    }

    const handleSubmit = e => {
        e.preventDefault()
        if (validate()) {
            editRecord(values);
        }
    }

    const item = values; // used for easier referencing (matches table item)

    return (
        <Form onSubmit={handleSubmit} open={openModal}> 
            <Grid>
                <Controls.Input
                    name="tankName"
                    label="Tank Name"
                    value={item.tankName}
                    onChange={handleInputChange}
                    error={errors.tankName}
                />
            </Grid>
            <Grid>
                    <Controls.Button
                        type="submit"
                        text="Submit"
                    />
                    <Controls.Button
                        text="Cancel" 
                        color="default"
                        onClick={()=>{setOpenModal(false)}}
                    />
            </Grid>
        </Form>
    )
}

Input.js (I can’t seem to find a way to control the Material UI TextFields and keep getting the console error above)

export default function Input(props) {

    const { error=null, label, name, onChange, value, ...other } = props;
    return (
        <TextField
            variant="outlined"
            label={label}
            name={name}
            value={value}
            defaultValue=''
            onChange={onChange}
            {...other}
            {...(error && {error:true,helperText:error})}
        />
    )
}

My company is only wanting a Read and an Update function, since Creating and Deletion will be handled another ways, so this is my final hangup. I think I am close, but I am missing something.

Can anyone point me in the right direction?

THANKS!!!!

CodePudding user response:

If you want to write an update request you would use axios.put to send the data to your back-end.

In your handleSubmit function you do:

let response = await axios.put('http://-------/api/tanks', { name: 'tank' });

(The second parameter is an object that needs to contain all the form data fields)

Also make sure you call e.preventDefault() in the handleSubmit function so you don't accidentally navigate elsewhere.

Then you will update your database or whatever using your back-end.

CodePudding user response:

for update you should use put or patch method and you should send id of item you want to update in request url. I insert 2 example here. this is for put:

const res = await axios.put('/api/article/123', {
    title: 'Making PUT Requests with Axios',
    status: 'published'
});

this is for patch:

const res = await axios.patch('/api/article/123', {
    title: 'Making PUT Requests with Axios',
    status: 'published'
});
  • Related