ReactJs: difficulty in resetting input field to empty string

I have an application using React v 0.13.1 (Old version). I am struggling to update my input field to "" after retrieving the updated value from the database.

Scenario: I am updating the input fields by clicking on the button named "Pull". This button's function is to fetch data from a separate database and then save the data in my database to update the input fields' values.

Child Component code:

<div>
  <div
    style={this.props.Styles.divItem}
    data-id={this.props.AddressArray["flat_no"]}
  >
    <div style={this.props.Styles.label}>Flat no.</div>
    <Input
      Type="text"
      Value={this._getValue(this.props.AddressArray["flat_no"])}
      ValueChanged={(value) =>
        this._DataItemValueChanged(value, this.props.AddressArray["flat_no"])
      }
    />
  </div>
</div>;

Method to retrieve input field value

    _getValue(itemId) {
        
        var currentValue = this.props.Details[this.props.Section][itemId];

        if(currentValue === undefined) {
            return "";
        }

        return currentValue.Value;
    },

There is a separate method to fetch data from the database and populate props, which is working fine. However, the input field does not update if it is blank i.e. "". It will update if it has any value like 9. Also, it will reset to blank after pulling data only if I refresh the page, otherwise it will retain its previous value.

Can anyone provide guidance on how to resolve this issue? Thank you in advance

Answer №1

Let's figure out why it isn't working

  • You may be missing the handleInputChange handler

Let's find a solution for this issue

  • Consider ShowEdit as your component name
  • There is a loader to fetch data from your local database before rendering the component
  • There is an action method for form submission
  • isPull state variable to fetch data from a separate database and re-render the component
  • navigator is used to reset after form submission

import {Form, useActionData, useLoaderData, useNavigate} from "react-router-dom";
import {useEffect, useState} from "react";
import 'react-toastify/dist/ReactToastify.css';
import {Button} from "react-bootstrap";

function ShowEdit() {

    const actionDataAfterSave = useActionData();
    const flat = useLoaderData();
    const navigator = useNavigate();
    const [formData, setFormData] = useState(flat);
    const [isPull, setIsPull] = useState(false);

    useEffect(() => {

        let flat_no = flat.flat_no;
        let url = 'url-to-your-separate-db-application/get-flat-info?flat_no='+flat_no;
        let flatFromRemoteDb = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-type': 'application/json'
            }
        }).then(response => response.json());
        setFormData(flatFromRemoteDb);

    }, [setIsPull]);


    useEffect(() => {

         if(actionDataAfterSave) {
             // reset
             navigator('/show-edit')
         }

    }, [actionDataAfterSave]);


    const onPullHandaler = () => {
        setIsPull(true);

    }
    const handleInputChange = (e) => {
        const {name, value} = e.target;
        setFormData((previousState) => {
            return {...previousState, [name]: value}
        })
    }



    return (
        <>

            <Form method='post'>


                <div className="mb-3">
                    <label htmlFor="name" className="form-label">
                        Flat no.
                    </label>
                    <input
                        type="text"
                        className="form-control"
                        name="name"
                        value={formData.flat_no}
                        onChange={handleInputChange}
                    />
                </div>

                <div className="mb-3">
                    Other form fields here
                </div>


                <Button variant="primary" onClick={onPullHandaler}>
                    Pull
                </Button>
                <Button type='submit' variant="primary">
                    Submit
                </Button>


            </Form>

        </>
    );
}

export default ShowEdit;

export async function loader({params}) {

    let flat_no = params.flat_no;
    let url = 'url-to-your-local-db-application/get-flat-info?flat_no=' + flat_no;
    let flat = await fetch(url, {
        method: 'GET',
        headers: {
            'Content-type': 'application/json'
        }
    }).then(response => response.json());

    return flat;
}

export const action = async ({request}) => {
    let flat;
    let reqObject = {}
    const formData = await request.formData();
    formData.forEach((value, key) => (reqObject[key] = value));

    let url = reqObject.id ? `path-to-your-local-db-update-action` : `path-to-your-local-db-save-action`;
    let method = reqObject.id ? 'PUT' : 'POST';


    try{
        flat = await fetch(url, {
            method: method,
            body: JSON.stringify(reqObject),
            headers: {
                'Content-type': 'application/json'
            }
        }).then(response => response.json());

    }
    catch (e) {
        console.log(e);
        return {success: 0, msg: 'Something went wrong.'}
    }

    return flat;
}

  • Your router configuration should look like this in main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import {createBrowserRouter, RouterProvider} from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';

import {action as myAction, loader as myLoader} from './ShowEdit.jsx';
import ShowEdit from "./components/routeComponents/ShowEdit.jsx";
import Home from "./components/routeComponents/Home.jsx";

const router = createBrowserRouter([
    {
        path: '/', element: <Home/>
    },

    {
        path: '/', element: <ShowEdit />,
        loader: myLoader,
        action: myAction
    }

]);


ReactDOM.createRoot(document.getElementById('root')).render(
    <React.StrictMode>
        <RouterProvider router={router} />
    </React.StrictMode>,
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Gleaming R: Warning prompt or modal box input: invalid

In the process of developing a basic application, I am seeking to implement a pop-up notification for invalid inputs. By referencing the suggestion provided in #1656, I have come up with an example that introduces a visually appealing background color when ...

What is the best way to perfectly align an SVG inside its container?

Is there a way to horizontally center this SVG within .svg_wrapper? .svg_wrapper { border: 1px solid grey; width: 200px; } <div class="svg_wrapper"> <svg viewBox="0 0 600 425"> <path d="M 175, 175 m 0, -75 a 75,75 0 1,0 ...

"Using ng-click to access values from other elements in AngularJS

Can someone help me retrieve the value of an input field when a button is clicked? Here is my controller code: app.controller('MainCtrl', function($scope) { $scope.test = function(val) { alert(val); } }); This is my HTML snippet: < ...

Is there a way to alter the color of radio buttons?

Is there a way to use CSS to change the background color of a radio button? I've searched online, but all the solutions I found involve JavaScript, which I don't fully understand. I attempted this CSS code, but it didn't have the desired eff ...

The steps to rotate a component in Material-UI version 5

I have a custom SVG component with spinning animation: export const Spinner = ({ color, size }) => ( <svg ref={ref} version="1.0" width={size} height={size} viewBox="0 0 150.000000 150.000000" preserveAspectRatio=" ...

Using a PHP WordPress Loop, eliminate the comma following the final object in the Schema array

My Google Schema Markup for a "Product" includes a loop that displays "Reviews". Below is an excerpt of the code: "review": [ <?php $args = array( 'post_type' => 'my_reviews', & ...

Creating an anonymous component in Vue.js involves enclosing the received slots (vnodes) within a wrapper component

Is there a way to wrap two specified named slots, slotOne and slotTwo, which are located in the child component at this.$scopedSlots.slotOne and this.$scopedSlots.slotTwo respectively? I would like to then conditionally render these slots (vnodes) as shown ...

Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query. Here's a snippet of my code: categoryMap = new Map<Number, String>(); //called onInit ...

Arranging Divs next to each other, ensuring uniform column heights, within a ContentPlaceHolder in ASP.NET

I am attempting to create a layout with three columns. The left and right columns will each contain a button that should remain aligned with the outer border of the container. In the center column, there will be an asp:Table generated dynamically, ranging ...

What is the best way to ensure that the width of a div fills its parent container?

I need my divs(.give, .sep, .take) to completely fill the width of its parent container (.trade). This is the HTML code: <div class="trade"> <div class="give"></div> <div class="sep"></div> ...

Showing formatted JSON in the view using ASP.NET MVC

Is there a method to modify JSON for presentation in the interface? I am looking for a way to automatically update my API documentation when adding new properties. It would be great if I could also apply CSS styling to certain elements. This feature is som ...

Customize Zurb Foundation: Applying styles to specific child elements based on current screen size (large, medium, small)

For wide displays, I aim to give a distinct border to each 7th element. However, on smaller screens, I wish to apply these styles to every 4th element instead. Is there a way for me to nest my styles within .small, .medium, and .large classes? ...

Error: The function exec in matchExpr[type] is not defined

I made some changes to Object.prototype and now I'm running into errors with jQuery's methods on selectors. The error message I'm getting is: Uncaught TypeError: matchExpr[type].exec is not a function Additionally, when trying to use $.po ...

Error Installing Node Sass

When attempting to install Node sass in my react app using the command npm install node-sass I encountered an error message. The error advised me to upgrade to version 7 or higher. It mentioned that older versions might use Math.random() in specific s ...

adjusting the size of the sidebar at the top to ensure that it does not overlap the top menu

I have a sidebar on my page that opens vertically when I click a button. The sidebar covers the company logo and name, so I want to make it smaller. Here is the code for the sidebar: <body> <nav class="navbar navbar-dark bg-dark" ...

New solution for Java applet requiring communication with browser using JavaScript

Within our web platform, we have been utilizing a Java applet to interact with the MS Word application using jacob jar. This allows users to open, edit, and automatically upload files to the server upon saving. However, due to Google Chrome discontinuing ...

What is the equivalent of {...props} in React for destructuring props in Vue?

When working in React, I can destructure props with ease: function MyComponent() { const myProp = { cx: '50%', cy: '50%', r: '45%', 'stroke-width': '10%' } return ( <svg> ...

What is the process for submitting a record to a table following the activation of a JavaScript link or button

I am working on creating a like-unlike button below each post for registered users to interact with. I have successfully created the button itself, but now I need to figure out how to store records when a user clicks the button. My idea is to utilize a tab ...

Incorporating the FLEX property into my code has been a challenge as it is not functioning properly on iOS 7 and 8 devices. Does anyone have any tips or suggestions on how to

While utilizing FLEX in my code, I noticed that the output is not what I expected on iOS 7/8 devices. <div className="modal-row"> <div className="col1"> <span>{dict.YourServiceNumber}</span> </div> <div ...

tips for displaying a label and text side by side on a single line

Is there a way to keep my label and text on the same line by adjusting the CSS? I've tried using float based on suggestions from other posts, but they still end up on different lines. .indentColumn { width: 71px; padding-top: 5%; } .labelColumn ...