Home > Back-end >  React: How to refresh the list on form submit without refreshing the page?
React: How to refresh the list on form submit without refreshing the page?

Time:11-20

I am displaying the data in the list with sort order in the textbox. User can change the order and click on submit will save the changed order in the database. list will be displaying in the new order on page refresh. Issue: How to refresh the list on form submit Without Page Refresh. Please help. Please find my sandbox:https://codesandbox.io/s/gallant-morning-k4emln

import React from "react";
import XMLParser from "react-xml-parser";
const data = `<?xml version="1.0"?>
<Category>
<description description-id="11" display-sequence="2">testing</description>
<description description-id="15" display-sequence="5">Guide</description>
<description description-id="20" display-sequence="7">test</description>
<description description-id="25" display-sequence="10">Guide</description>
<description description-id="30" display-sequence="12">test</description>
</Category>
</xml>`;
const REQUEST_URL = "";
const axios = {
 get: () =>
   new Promise((resolve) => {
     setTimeout(resolve, 1000, { data });
   })
};
class Order_Descriptions extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     proddescriptions: [],
     proddescription_id: "",
     display_sequence: ""
   };
 }

 handleChange = (event) => {
   const { name, value } = event.target;
   this.setState((prevState) => ({
     proddescriptions: prevState.proddescriptions.map((el) =>
       el.id === name
         ? {
             ...el,
             sequence: value
           }
         : el
     )
   }));
 };

 componentDidMount() {
   this.getlistofdescriptions();
 }

 getlistofdescriptions() {
   axios
     .get(REQUEST_URL, { "Content-Type": "application/xml; charset=utf-8" })
     .then((response) => {
       const jsonDataFromXml = new XMLParser().parseFromString(data);
       const descriptions = jsonDataFromXml.getElementsByTagName(
         "description"
       );
       /*  console.log(descriptions);
         this.setState({
           proddescriptions: jsonDataFromXml.getElementsByTagName("description")
         });
       });
            const URL = "/descriptionlist"
             axios
                   .get(URL, { 'withCredentials': 'true' })
                                .then((response) => {
             const jsonDataFromXml = new XMLParser().parseFromString(response.data);
             const descriptions = jsonDataFromXml.getElementsByTagName(
"description" )*/
       const proddescriptions = descriptions.map(({ attributes, value }) => ({
         id: attributes["description-id"],
         sequence: attributes["display-sequence"],
         value
       }));
       this.setState({
         proddescriptions
       });
     });
 }
 handleSubmit = (event) => {
   event.preventDefault();
   const ProdDescriptions = this.state.proddescriptions;
   const URL = "/descriptionlist/order";
   const data = {
     ProdDescriptions
   };

   fetch(URL, {
     method: "POST",
     headers: { "Content-Type": "application/json" },
     credentials: "include",
     body: JSON.stringify(data)
   })
     .then((response) => response.json())
     .then((data) => {
       this.setState({
         ValidationStatus: data
       });
     })
     .catch((error) => console.error("Error:", error));
 };

 render() {
   return (
     <div>
       <form onSubmit={this.handleSubmit}>
         <div>
           <ul style={{ listStyle: "none" }}>
             {this.state.proddescriptions.map((item) => (
               <li key={item.id}>
                 <label>
                   <input
                     type="text"
                     name={item.id}
                     size="5"
                     maxLength="3"
                     value={item.sequence}
                     onChange={this.handleChange}
                   />
                 </label>
                 &nbsp;{item.value}{" "}
               </li>
             ))}
           </ul>
         </div>
         <input type="submit" name="submit" value="Submit" id="btnsubmit" />
       </form>
     </div>
   );
 }
}
export default function App() {
 return (
   <div className="App">
     <h1>Sort Data</h1>
     <h5>Submit button sort list without page refresh</h5>
     <Order_Descriptions />
   </div>
 );
}

thanks

CodePudding user response:

You can sort proddescriptions state on fetch success

here is what I did

First, I add compare function to use it in sort function

compare(a, b) {
  if (parseInt(a.sequence, 10) > parseInt(b.sequence, 10)) return 1;
  if (parseInt(a.sequence, 10) < parseInt(b.sequence, 10)) return -1;
  return 0;
}

and then sort proddescriptions state in fetch success:

    this.setState({ proddescriptions: ProdDescriptions.sort(compare) });

here you can see the result :

https://codesandbox.io/s/late-tdd-rnzr6e?file=/src/App.js

CodePudding user response:

Call the this.getlistofdescriptions() when the post request succeed (the place where you set the validation status after the request).

  • Related