Search code examples
javascriptreactjsreact-routerreact-router-domreach-router

Reach router refresh page


Setup: I have a form that send data to an action creator, which in turn submits to an API and gets the result. What I want is when the form submits successfully, to refresh the form with blank inputs.

This is how the component looks like

import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { addNewProduct } from "../../redux/actions";

class Admin extends Component {

    state = {
        ProductName: ""
    };

    onChange = e => {
        e.preventDefault()
        this.setState({
            [e.target.name]: e.target.value
        })
    }

    handleProductSubmit = (event) => {
        event.preventDefault();
        this.props.addNewProduct(
            this.state.ProductName,
        );
    }

    render() {
        return (
            <div>
                {/* Form ends */}
                <form onSubmit={this.handleProductSubmit} autoComplete="off">

                        <input
                            type="text"
                            value={this.state.ProductName}
                            name="ProductName"
                            onChange={this.onChange}
                        />

                    <button type="submit" className="btn btn-dark">
                        Upload Product
                    </button>
                </form>
                {/* Form Ends */}

            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({ addNewProduct, createNewLogin }, dispatch);
};

export default connect(null, mapDispatchToProps)(Admin);

This is the result of the console.log(this.props)

location: Object { pathname: "/Home/admin", href: "http://localhost:3000/Home/admin", origin: "http://localhost:3000", … }
navigate: navigate(to, options)
​​
length: 2
​​
name: "navigate"
​​
prototype: Object { … }
​​
<prototype>: ()

This is how the actionCreator looks like

export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {

    const productData = new FormData();
    productData.append("ProductName", ProductName)
    axios.post("http://localhost:4500/products/", productData,
        {
            headers: {
                "Content-Type": "multipart/form-data",
                "Authorization": localStorage.getItem("Authorization")
            }
        })
        .then(res => {
            console.log(res.data)
            setTimeout(() => {
                console.log("doing the timeout")
                navigate("/Home/admin")}, 1500);

        })
        .catch(err =>
            console.log(`The error we're getting from the backend--->${err}`))
};

Current behavior

When I submit the form and the API return 201, the page does not refresh and the inputs do not go blank

Expected behavior:

When I get a 201 from the API, the page should refresh and the inputs should be blank.

Please help me how to achieve this.


Solution

  • Using navigate to move the same url or page won't remount the page and reset your field values.

    Its better is you actually return a promise from your action creator and reset the state yourself

    export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
    
        const productData = new FormData();
        productData.append("ProductName", ProductName)
        return axios.post("http://localhost:4500/products/", productData,
            {
                headers: {
                    "Content-Type": "multipart/form-data",
                    "Authorization": localStorage.getItem("Authorization")
                }
            })
            .then(res => {
                console.log(res.data)   
            })
            .catch(err =>
                console.log(`The error we're getting from the backend--->${err}`))
    };
    

    In the component

    handleProductSubmit = (event) => {
        event.preventDefault();
        this.props.addNewProduct(
            this.state.ProductName,
        ).then(() => {
            this.setState({ProductName: ""})
        });
    }