MontyGoldy
MontyGoldy

Reputation: 749

React/Redux Unable to keep previous state of search input

I am trying to save recent searches in local storage.

Reducer.js

const initialState = {
  venues: [],
  searches: [],
};

const venueReducer = (state = initialState, action) => {
  switch (action.type) {
    case RECENT_SEARCHES:
      return {
        ...state,
        searches: [
          ...state,
          { near: action.payload.location, query: action.payload.place },
        ],
      };
  }
};

Action.js

export const fetchVenues = (place, location) => dispatch => {
  dispatch({ type: FETCH_VENUE_REQUESTED })
  dispatch({ type: RECENT_SEARCHES, payload: { place, location } })
};

Right now I am getting the user input and saving it to the searches array in reducer but it's not keeping the previous state. Only shows the current user input.

Upvotes: 0

Views: 127

Answers (1)

Anthony
Anthony

Reputation: 6482

When you spread the searches, you need to do:

[ ...state.searches,

Instead of just:

[ ...state,

As that will put state.venues (Array) and state.searches (Array) in your state.searches

Upvotes: 1

Related Questions