Reza Adha Hamonangan
Reza Adha Hamonangan

Reputation: 94

How to make my component re render after updating props from selector in react and redux-saga?

i am a newbie in react, redux-saga library so i am struggling to solve this problem ...

so i have this component. i use api for fetching, removing data with redux-saga.

export class ExampleComponent extends React.Component {
  constructor() {
    super(props);
    this.props.getList();
  }

  handleClick(value) {
    this.props.deleteFromList(value);
  }

  render() {
    if (this.props.isFetched) {
      return (
        this.props.list.map( (value, i) => {
          <button onClick={this.handleClick.bind(this, value)}>
            {value}
          </button>
        } );
      );
    }

    return <div><h1>Fetching list...</h1></div>;
  }
}

ExampleComponent.propTypes = {
  list: React.PropTypes.array,
  isFetched: React.PropTypes.bool,
  getListAction: React.PropTypes.func,
  deleteFromListAction: React.PropTypes.func,
};

export function mapDispatchToProps(dispatch) {
  return {
    getList: () => dispatch(getListAction()),
    deleteFromList: (id) => dispatch(deleteFromListAction(id));
  };
}

const mapStateToProps = createStructuredSelector({
  list: selectList(),
  isFetched: selectIsFetched(),
});

export default connect(mapStateToProps, mapDispatchToProps)(ExampleComponent);

so when the data is loaded, i tried to click to trigger event onClick on button. and the delete action is success and the record is deleted from db.but the view is not updated so when i refreshed the browser the clicked button has been removed.

so how do i make my component to be auto updated when i add, remove data? Thank you for your time and i hope you can help me solve this T_T

Upvotes: 3

Views: 4236

Answers (1)

epikhighs
epikhighs

Reputation: 516

Your component will not update unless there is a change to your state. As you've noticed, there is a change in the DB, but there is no change in your redux store state, specifically your selectedList.

So what you'll need to do is wait for the DB delete to be successful, then you can dispatch another action to fetch your selected list. The new list would be different from your original list and so your component would refresh.

export function* deleteSaga (action) {
    yield call(deleteDataRequest)
    yield put(FETCH_LIST);
}

Sagas make this kind of flow control quite easy, since your DELETE request can be yielded and then you can PUT a fetch action after your DELETE.

This is just one potential solution. But hopefully, it'll point you into the direction of what you need to do.

Upvotes: 3

Related Questions