page has to be refresh to show updated data in react?

Viewed 92

I have a form with two input fields

 <form method="POST" onSubmit={bnkSubmit}>
        <input type="text"  name="bnk" autoComplete="off" />
          <input type="text"  name="ifsc" autoComplete="off" />&nbsp;
           <input type="submit" value="Add" />
   </form>

data gets saved in the database but the problem is I have to refresh the page to get updated data

const bnkSubmit = async (e) =>{

    e.preventDefault()
    
    const {bnk, ifsc, user} = bank

    const res = await fetch('/addDetails', {

        method:"POST",
        headers:{
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
  
            bnk, ifsc, user
            
          })
    })

    const data = await res.json()

    if(res.status === 402 || !data)
    {
        alert("Please fill all details")

    }else{

        alert("Bank details added sucesfully")
        setbank({...bank, bnk:"", ifsc:""})
        e.target.reset()
       
    }

}

what I want is to update my table without refreshing the page where I'm showing the updated data.

 {resData.map((resData)=> 
                        <tr>
                            <td>{resData.acc_no}</td>
                            <td>{resData.ifsc}</td>
                            <td><button>Edit</button></td>
                            <td><button>Delete</button></td>
                        </tr>
                        )}
2 Answers

Assuming you are using useState hook. You should also have resData as state as well. Or please share snippet of how you are managing resData.

  const [bank, setbank] = useState({ bnk: "", ifsc: "" })
  const [resData, setData] = useState([])

I can see that you are trying to map resData for displaying table data but in your code i can't see you are setting state for resData.

for updating table without refreshing page you need to set data in State for re-render .

//Declare initial state
const [resData, setresData] = useState([]);

//set state for resData
setresData(data);

Related