0

I have a Node backend with React frontend. When a user creates a movie review, the post request gets handled with axios. Right after that, the user gets taken to a homepage but the review is not there yet. When I refresh the page, the review appears.

How can I fix this issue so that the user doesn't have to get confused when, after submitting, they don't see the review in homepage? Should I refetch every time a user hits the homepage? Or is React doing it behind the scenes but early so the review isn't registered?

My redux request code:

the reducer

export const postNewReview = review => (dispatch, getState) => {
    return apiCall("post", `http://localhost:8000/review`, review)
      .then(res => {})
      .catch(err => addError(err.message));
  };

the api call function

export function apiCall(method, path, data){
    return new Promise((resolve,reject) => {
        return axios[method.toLowerCase()](path,data)
            .then(res => {
                return resolve(res.data);
            })
            .catch(err => {
                return reject(err.response.data.error);
            });
    });
}

handling submitting

handleSubmit = (e) => {
        e.preventDefault();    
        this.props.postNewReview(this.state);
        this.setState({user: '', title: '', image: '', text: ''});
        this.props.history.push('/');
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Why don't you use .then in handleSubmit? Really this is another https://stackoverflow.com/q/14220321/3001761 – jonrsharpe Dec 20 '19 at 22:19
  • What you say is a reducer is not, but an async action creator (I guees you are using redux-thunk) – Alexander Vidaurre Arroyo Dec 20 '19 at 22:43
  • You're not using the promise returned from `this.props.postNewReview()` to know when that's done and wait before calling `this.props.history.push('/');` which is presumably what triggers the page to refresh (before the posting of the new review is done). – jfriend00 Dec 20 '19 at 22:46

0 Answers0