mark ortiz
mark ortiz

Reputation: 739

react-redux with redux thunk with Router

I have this git repo i created https://github.com/markortiz905/emp-app

Ive been practicing reactjs and wanted to learn about redux-thunk, at first kinda easy but I fall short on understanding how it works on routes as well.

My investigation led me to think that data fetched from server is not triggering update component due to routing ?

If anyone have time to take a look on my repo its just few files and codes simple fetch empmloyee and display on view

Heres my reducer.js snippet

const initStates = {
    employees: [],
    loading: true
};

function rootReducer(state = initStates, action) { 
    console.log(state.employees);
    if (action.type == UPDATE_EMPLOYEES) {
        state.employees = action.payload;
    } else if (action.type == LOADING) {
        state.loading = action.payload;
    }
    //means something happen bad
    return state;
}

Upvotes: 0

Views: 112

Answers (1)

mark ortiz
mark ortiz

Reputation: 739

I just found out whats wrong, it seems that I am doing it wrong from the very start in my reducer script This is wrong, I am updating employees from the const variable but const cant be updated right? once you’ve assigned a value to a variable using const, you can’t reassign it to a new value. source - https://tylermcginnis.com/var-let-const/

const initStates = {
    employees: [],
    loading: true
};

function rootReducer(state = initStates, action) {
    console.log(state.employees);
    if (action.type == UPDATE_EMPLOYEES) {
        state.employees = action.payload;
    } else if (action.type == LOADING) {
        state.loading = action.payload;
    }
    //means something happen bad
    return state;
}

I changed my reducer to return the new object instead.

function rootReducer(state = initStates, action) {
  switch (action.type) {
    case UPDATE_EMPLOYEES_STARTED:
      return {
        ...state,
        loading: true,
        employees: null,
      };
    case UPDATE_EMPLOYEES:
      return {
        ...state,
        loading: false,
        error: null,
        employees: action.payload,
      };
    case UPDATE_EMPLOYEES_ENDED:
      return {
        ...state,
        loading: false,
        employees: [...state.employees],
      };
    default:
      return state;
  }
}

Upvotes: 1

Related Questions