Reputation: 11931
I have a record with two buttons, on click on Accept
button should send the data back to server and display the text to Save
and should not change the text afterwards ( should change only for clicked buttons).
In the below example, it is changing the text during on click, which is fine, but while refreshing the page it set back the text to Accept
. Could someone please advise on how can I fix this ?
import { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [acceptPlayer, setAcceptPlayer] = useState("Accept");
const postData = (e) => {
const text = "Save";
setAcceptPlayer(text);
};
return (
<div className="App">
<div>
<button onClick={postData} value="accept">
{acceptPlayer}
</button>
</div>
</div>
);
}
https://codesandbox.io/s/admiring-austin-1w1g38?file=/src/App.js
Upvotes: 0
Views: 196
Reputation: 10071
There is nothing wrong with this code. It's the expected behavior of the react. React or any other framework does not persist state on refresh That's the responsibility of the BE.
Solution: When you can get API to show the data on the page, In the API response, you can return the data in the following format:
{
isAccepted: false,
//...something else
}
When you click on accept button and call the API BE is responsible for updating the isAccepted flag from the next time the API is called. You will get the following response:
{
isAccepted: true,
//...something else
}
Based on isAccepted flag you can toggle the button text.
Upvotes: 1
Reputation: 1201
Of course, it would go back to Accept
because react only stores state locally. So every time you refresh the page it will go back to its initial state
.
So if you want to get the updated state in your component then you have to fetch the latest data from the database in useEffect
and have to set it to a state.
Upvotes: 1