Martin
Martin

Reputation: 445

React - update component when different component changed state

I have in header component dropdown which behave like a filter for whole my application. Lets say I got grid component in my layout its filled with some data, for example list of cars which were available in some year. When I select from my dropdown in header year, I want to update my grid component to contain only cars which were available in selected year.

Here is my reducer with action creator for dropdown in header component. I removed some code for brevity.

export interface IImporterSelectorContextState {
    dataQuery?: ServiceApi.IDataQuery;
    data?: any[];
    context?: ServiceApi.IDocumentContext
}    
type KnownAction = 
    IChangeCurrentContext

export const actionCreators = {
    changeYearContext: (context: ServiceApi.IDocumentContext) : AppThunkAction<KnownAction> => (dispatch, getState) => {
        dispatch(changeCurrentContext(context));
    }
}

const unloadedState: IImporterSelectorContextState = {
   //removed for brevity
};

export const reducer: Reducer<IImporterSelectorContextState> = (state: IImporterSelectorContextState,
    incomingAction: Action) => {

    const action = incomingAction as KnownAction;
    switch (action.type) {
        case CHANGE_CURRENT_CONTEXT:
            return {
                ...state,
                context: action.context
            }
        default:
            const exhaustiveCheck: never = action;
    }
    return state || unloadedState;
}

When year is selected, changeYearContext function is called, my state is set to new values for header component. I dont know exactly how can I update my grid component where cars are shown. To get new data based on my filter, i have to send new request (got button for that) to get new data, but I want to refresh data when new year from dropdown is selected. How can I accomplish that?

Upvotes: 0

Views: 79

Answers (1)

DevTheJo
DevTheJo

Reputation: 2507

You can achieve this by two way:

Method 1: the simplest, bind an event hanlder using onChange property of your select component, like this:

import {Component} from 'react'
class MyHeaderComponent extends Component{
  render(){
    return (
      <select onChange={(e)=>this.changeYearHandler(e.target.value)}>
        <option></option>
        ...
      </select>
    )
  }
  changeYearHandler(value){
    fetch(MY_API_URI, /* and pass value with post json or other way*/).then(data=>{
      // give it to redux via prop bound with react-redux's connect method
      this.props.changeYearContext(data)
    })
  }
}

Method 2: use redux-saga and implement request as a side effect of changing the redux state, with this method, first, you change the year state, and then, your data is loaded and pushed to the state, I suggest you to read the doc from https://github.com/redux-saga/redux-saga

Upvotes: 1

Related Questions