Jack23
Jack23

Reputation: 1396

ReactJS: Update values without reload the page

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()
      }
    }

Upvotes: 1

Views: 835

Answers (1)

LonelyPrincess
LonelyPrincess

Reputation: 461

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
  })
}

Upvotes: 1

Related Questions