0

My setup is I have 2 main component, I have the NewForm and MainPage. When a user goes to NewForm, it will unmount the MainPage and vice versa

The NewForm is connected to a Web API so when the user submits, it sends the Data to the Web API and brings back a success response and redirects back to the Main Page.

While the MainPage has a table that displays all the Data also coming from the WebAPI. For now I made it to call the Web API every time it is mounted.

My current dillema is that after a user submits a form, it won't display the newly created data because it was still processing when it gets redirected to the MainPage and gets its data from WebAPI.

So on my research the best method I got is using Promise:

    newForm() {
    this.props.newDataForm(this.formdata).then(()=>{ 
        this.props.changePage("MainPage");
    }); 
}

But when I try running it, I'm getting:

TypeError: this.props.newDataForm(...).then is not a function

My action looks like:

export const newDataForm = (postData) => dispatch => {
return () => {fetch('http://localhost:81/api/value', {
method: 'POST', 
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(postData)}).then(function (data) {
  console.log('Request succeeded with JSON response', data);          
  dispatch({
    type: types.NEW_FORM,
    payload: data
})
}).catch(function (error) {
  console.log('Request failed', error);
})}

};

1 Answers1

3

You need to return fetch

export const newDataForm = (postData) => dispatch => {
return () => fetch('http://localhost:81/api/value', {
method: 'POST', 
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(postData)}).then(function (data) {
  console.log('Request succeeded with JSON response', data);          
  dispatch({
    type: types.NEW_FORM,
    payload: data
})
}).catch(function (error) {
  console.log('Request failed', error);
})}
};
marzelin
  • 7,822
  • 1
  • 18
  • 35