S
S
SergeyMina2015-09-06 22:40:55
JavaScript
SergeyMina, 2015-09-06 22:40:55

How to change/select city in React.js with Redux in RoR?

Hello.
I am learning React with flux approach (Redux).
On the backend I have RoR.
Task: change the city and record it in the session.
Previously, on the view, I had this:

- city.each do |name|
    = link_to name.city, controller: 'application', action: 'switch_city', city: name.city

Method in controller:
def switch_city
    session[:city] = params[:city] if params[:city]
    redirect_to root_url
  end

Depending on the city, additional information was pulled onto the page.
After I started porting to React, general questions began to arise. In fairness, how to do what is above on React'e.
What is on React:
Action from which objects come to the reducer. In the component in componentDidMount, the whole thing is loaded. Those. when the component is loaded, everything is fine on the view. But now there is a task to change the city and then the question arises how to do it?
As I imagine it: It is necessary to pass a parameter with value to the action and load data depending on it.
Like this in an action:
export function city(valueCity) {
    ...
}

Or does it need to be done somehow in the reducer? In general, I'm not catching up here how to do it. And the examples don't help.
If I misunderstand the concept, please correct me.
For clarity, I will add an operating time on React.
Action
export function city() {
  return dispatch => {
    dispatch({
      type: 'LOAD'
    });
    axios.get(
      Routes.root_path(), { headers: { 'Accept': 'application/json' } } 
    ).then(result => {
        dispatch({
          type: 'LOAD_SUCCESS',
          city: result.city,
        })
      })
  }
}

Reducer
export default function cityData(state, action) {
  switch (action.type) {
    ...
    case LOAD_SUCCESS:
      return {
        ...state,
        city: action.city,
      };

    default:
      return state;
  }
}

Component
class App extends Component {
  ...

  componentDidMount() {
    ...
    dispatch( cityData() );
  }

  onLoadCity() {
    ...
    dispatch( cityData() );
  }

  render() {
    ...

    return (
      <div>
          <ComponentBar onClick={this.onLoadCity}/>
      </div>
    );
  }
}

ComponentBar
export default class ComponentBar extends Component {
  render() {
    return (
      <div>
        <button onClick={this.props.onClick}>
          Выбрать город
        </button>
      </div>
    );
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2015-09-07
@SergeyMina

Generally correct RESTful should not depend on cookies and session.
Accordingly, it is better to store the city on the client in localStorage . When loading additional information, you need to specify it as a parameter in the request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question