xristlxcv
xristlxcv

Reputation: 41

Redux-React populate initialState with api call

populate my initialState with json api call from a component or from here

const initialState = {
      myvalues: [] ---->here i want to populate this array
    };

const reducer = (state = initialState, action) => {
  const newState = { ...state };
  switch (action.type) {
    case "Update":
      console.log(newState);
    // newState.myvalues = action.key.title.value;
    default:
      return newState;
  }
};
export default reducer;

Upvotes: 1

Views: 1796

Answers (2)

jcal
jcal

Reputation: 875

To populate your initialState with data from an API, you can create e.g. an FETCH_INIT_DATA_ACTION, which get's dispatched right after you initialised your store.

// ...
const store = createStore(/* ... */)

store.dispatch({ type: 'FETCH_INIT_DATA_ACTION' })

// ...

whereas FETCH_INIT_DATA_ACTION triggers a redux-thunk, saga, effect or whatever you want to use.

Upvotes: 2

Ertan Hasani
Ertan Hasani

Reputation: 1773

You can do it like this:

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "Update":
      return { ...state, myvalues: action.payload }
    default:
      return state;
  }
};

And when you dispatch it you should put your API data in payload.

Upvotes: 0

Related Questions