Mvrocha
Mvrocha

Reputation: 393

Reducer doesn´t bring initialState

I am using a reducer to manage a varied of states on my application. But every time I add a new key to my initial state, like this:

const initialState = {
  loading: false,
  archiveTypes: [],
  archiveType: {
    id: null,
    name: '',
    local: '',
    description: '',
  }
}

The initialState never shows the new information until I dispatch some info to the reducer.

Is there a way to make it already start with all the information?

My full code:

import * as actionTypes from 'actions';
import produce from 'immer';

const initialState = {
  loading: false,
  archiveTypes: [],
  archiveType: {
    id: null,
    name: '',
    local: '',
    description: '',
  }
}

const archiveTypeReducer = produce((draft, action) => {

  switch (action.type) {

    case actionTypes.ARCHIVE_TYPE_GET_ALL_SUCCESS: {
      draft.loading = false;
      try {
        draft.archiveTypes = action.payload
      } catch (err) {
        console.log(`REDUCER ERROR ${err}`)
      }
      return draft;
    }

    case actionTypes.ARCHIVE_TYPE_GET_BY_ID_SUCCESS: {
      draft.loading = false;
      try {
        draft.archiveType = action.payload
      } catch (err) {
        console.log(`REDUCER ERROR ${err}`)
      }
      return draft;
    }

    case actionTypes.ARCHIVE_TYPE_REQUEST_FAILURE: {
      draft = initialState
      return draft
    }

    default: {
      return draft;
    }
  }
}, initialState);

export default archiveTypeReducer;

Upvotes: 0

Views: 79

Answers (3)

Piter
Piter

Reputation: 116

And one thing, you forgot set initiasState as default state(draft). produce((draft = initialState, action).

Upvotes: 0

machineghost
machineghost

Reputation: 35790

In a Redux app, your initial state is exactly that: your initial state. If you want to change your state after your page loads, you have to dispatch an action to do so.

If you want a way to completely reset your state, then you'll need to create a RESET_ALL_STATE action (or in your case, it seems your actionTypes.ARCHIVE_TYPE_REQUEST_FAILURE restores the initial state). But really that's pretty abnormal; normally you'll just want to use an ADD_SPECIFIC_DATA action.

Upvotes: 1

Piter
Piter

Reputation: 116

For example, you can call action in method of component live circle, like componentDidMount. Or react hooks, useEffect https://reactjs.org/docs/react-component.html#componentdidmount

Upvotes: 0

Related Questions