Optimistic Vs Pessimistic operations in REACT

Optimistic Vs Pessimistic operations in REACT

In react we are usually faced with CRUD operations on our state and the server, one will ask do i update the state of my app first before calling the server to implement the changes or i call the server then update the changes.

const [posts,setPosts]=useState([{post1},{post2},{post3},{post4}])
const handleDelete = async (postObj)=>{
await axios.delete(apiEndpoint + "/" + postObj.id)

const Filteredposts=posts.filter((post)=>post.id!==postObj.id)
setPosts(filteredPosts)

}

In the Above code we first delete from the server then update our state, if an error occurs as we are deleting from the server, the rest of the function won't be executed, this is what we call PESSIMISTIC updates, however OPTIMISTIC update is the direct opposite here will agree that a call to the server will always work so we update our state first then call the server. Even though the call to the server takes time OPTIMISTIC updates gives the user an illusion of a fast application cause we update the state first then called the server.

What happens if something goes wrong?

This is where we use our try catch block we store the initial value of the state in variable then try to call our server if it passes the try the state updates else the catch block takes the state back to it's initial value.

//THIS IS HOW WE IMPLEMENT OPTIMISTIC UPDATE
const handleDelete = async (postObj)=>{
 const OrginalPosts =posts; //from the state
 const Filteredposts=posts.filter((post)=>post.id!==postObj.id)
 setPosts(filteredPosts)
 try{
   await axios.delete(apiEndpoint + "/" + postObj.id)
 }
 catch(ex){
    setPosts(OrginalPosts)
 }
}

We first make a reference to the initial state, then update the state, then make a call to the server, if it fails set the state back to it's initial value.

While in Pessimistic we call the server first then set the state inside the try block after the server has been called. If it is not successful, our catch block still remains the the same and resets our state.

You see it's that simple. Happy Coding!