1

I have this problem, when I do a insert or a change about some data, to see the new data I need to reload the page while I would to update automatically the value without the need to reload the page. How can I do?

This is the part where the user click on submit and the post

_onSubmit(Document)
    {
        const self = this
        if ( !_.isEmpty(Document) )
        {
            //..
            if (Document && !_.isEmpty(Document.Anagraphics))
            {
                alertify.confirm(
                    utility.t('sureYouWanna_SAVE'),
                    () => {
                        const now = new Date();
                        Document._id = `PRODUCT:${new Date().getTime()}-${utility.CUID()}`
                        Document.CreationDate = now.toISOString()
                        Document.CategoryCode 
                        Document.Status = 'New';
                        Document.Type = 'PRODUCT';
                        self._POST(Document)
                    },
                    function(){}
                ).set('labels', {ok: utility.t('YES_SAVE'), cancel: utility.t('CANCEL')})
            }
            else
            {
                $methods.WarnMissingValues()
            }
        }
        else {
            $methods.WarnMissingValues()
        }
    }



_POST(Document)
    {
        console.log("DOCUMENT POST", Document)
        const self = this
        const auth = this.props.db.auth
        fetch(`${this.props.db.couch_db_host_url}requests`,{
            method: 'POST',
            credentials: 'include',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': 'Basic ' + btoa(`${auth.username}:${auth.password}`)
            },
            body: JSON.stringify(Document)
        })
        .then(response => {
            alertify.dismissAll()
            if(response.status > 299 || response.status < 200){
                alertify.error(utility.t('AN_ERROR_OCCURRED'))
                self._updateState({ submitSucceeded: false })
            }
            else{
                alertify.alert(utility.t('ITEM_EDITED_OK'), function(){})
                self.props.history.push({
                    pathname: RoutesIT.products_details
                })
            }
        })
        .catch((err, warning) => {
            if (err)
            {
                alertify.dismissAll()
                alertify.error(utility.t('AN_ERROR_OCCURRED'))
                console.log('_POST', err);
                self._updateState({ submitSucceeded: false })
            }
            else
            {
                console.log(warning)
                alertify.dismissAll()
                alertify.warning(utility.t(warning))
            }
        })
    }

How can I do to not reload the page to see the result of the post? Thank you

UPDATE:

In the page I have also:

function mapStateToProps(state) {
    const { app: { login, p, c, l, c_timestamp, p_timestamp, l_timestamp }, form } = state;
    return {
        db: login ? login.db : null,
        Sender: login ? login.Location : null,
        timestamp: login ? login.timestamp : null,
        [ FORM_NAME ]: form[FORM_NAME],
        products: p,
        locations: l,
        categories: c, 
        categories_timestamp: c_timestamp,
        products_timestamp: p_timestamp,
        locations_timestamp: l_timestamp,
        utente: login,
    };
}

while the reducers

case actions.CATE_UPDATE:
    {
      return {
        ...state,
        c: action.payload,
        c_timestamp: new Date().getTime()
      }
    }
10
  • You need to add the data to the state too, after you post the item to the api, from your example code, that is not clear how you store your existing data, I could not provide a working example. Commented May 21, 2020 at 8:18
  • If you use post method of HTML form then browser will force reload, you must return false in onSubmit event. I think you should use ajax to send your data to server, the page won't reload and you can't receiver response on callback ajax. Commented May 21, 2020 at 8:21
  • I use redux to save the state could be this the problem? Commented May 21, 2020 at 8:34
  • I don't understand how to do.. Which part I should see in your opinion? Commented May 21, 2020 at 8:37
  • You said you use Redux, right? Would you mind posting the code for your reducer, the part where you are updating the data? Reducers are often the root of errors like this, so it's a good place to start looking for the issue. Commented May 21, 2020 at 9:13

1 Answer 1

1

For what I can see in your code, the problem may lie in the fact that you're not dispatching any action when you submit the data.

Redux store can only be modified via actions, and since you're not triggering any, its contents are never being updated. This explains why your component is not updated in real time: your local data is never changing, so React is not aware of any updates. Things works when you reload the page because you're probably fetching the data from server, where the data did change during your POST request.

In order to fix this issue, you first need to pass a mapDispatchToProp to the your component, same as what you did with mapStateToProps:

connect(mapStateToProps, mapDispatchToProps)(YourComponent);

Inside of mapDispatchToProps, you have to return a property containing a function that will dispatch the CATE_UPDATE action you want to run:

const mapDispatchToProps = (dispatch) => ({
  cateUpdateAction: (payload) => dispatch({
    type: CATE_UPDATE,
    payload
  }),
});

Once you've done that, you'll be able to access this function from your component's props and call it inside of your _POST method.

if (response.status > 299 || response.status < 200){
  alertify.error(utility.t('AN_ERROR_OCCURRED'))
   self._updateState({ submitSucceeded: false })
} else {
  alertify.alert(utility.t('ITEM_EDITED_OK'), function(){})

  // Dispatch action to update data in Redux store
  self.props.cateUpdateAction(data_to_save);

  self.props.history.push({
    pathname: RoutesIT.products_details
  })
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, so I need to understand what insert in the "data_to_save"?
Because If i pass the document, when I click on save I receive this error: _POST ReferenceError: CATE_UPDATE is not defined
You should replace data_to_save with what you wanted to save in the store, what you expected the action.payload in your reducer to be. I don't really know what it is, that's logic inner to your application. :) As for that error, you probably haven't imported the CATE_UPDATE constant in the file where you defined mapDispatchToProps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.