2
votes

I have app, which loads the data from my server. I dispatch getData() action from my index file. I have couple reducers, joined with combineReducers into rootReducer.

I do get the data via getData. But how to dispatch the SET_DATA action, or simply change the state with the new data?

I can't call store.dispatch from the reducer and calling the action the way as I have it currently changes the data in my state, but doesn't redraw the page.

import { SYSTEM_FILTER, SET_DATA, GET_DATA, getData, setData } from '../actions/systemlist'
import rootReducer from './index'

const initialState = {
      systemFilters: true,
      systems: []
    };
export default function systemlist(state=initialState, action) {
  switch (action.type) {
    case SYSTEM_FILTER:
       var enabled=document.getElementById("filterSystems").checked;
       return {systemFilters: enabled, systems: state.systems}
    case GET_DATA:
       console.log("Getting data");
       $.getJSON("../data/systems.json", function(data) {
          data=data.sort(function(a, b) {
             var textA = a.name.toUpperCase();
             var textB = b.name.toUpperCase();
             return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
          });
          systemlist(state, {type: "SET_DATA", data: data});
       });
       return state
    case SET_DATA:
       console.log("Setting data");
       $("#systemsMenuCounter").html(action.data.length);
       return {systemFilters: state.systemFilters, systems: action.data}
    default:
      return state
  }
}
1

1 Answers

4
votes

first of all, your reducer functions should be pure. What does that mean? The redux documentation says:

For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

Without going too much into detail here, about the problem of redux in combination with async requests, i'd like to give you two examples of middleware, that are focused on solving the problems of asynchronicity.

  1. Thunk solves the problem with action creators that return functions to perform conditional dispatches.
  2. Sagas uses generator functions for chaining actions

There are several more ways of handling your problem that I have not mentioned yet, but I recommend the Redux Documentation (Async Actions) as a starting point!