Petter Östergren
Petter Östergren

Reputation: 1013

Accsessing values from an object/array redux store

Im trying to map an object of arrays?

console.log

I tried to map it over.

<ul>{categories.map(cat => <li key={cat.name}>{cat.name}</li>)}</ul>

But receives an error that it's not a function. I guess it is because its an object of arrays and map handles only pure arrays? But I'm not sure how I could use it.

Or could I return a different kind of object straight from my action/reducer, I am using redux-thunk and axios

API

const headers = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
  Authorization: 'jfaiwnfwvin',
}

export const fetchCategories = () => {
  return axios.get(`${API_URL}/categories`, { headers })
}

Action

export function getCategories() {
  const request = API.fetchCategories()

  return dispatch => {
    request.then(({ data }) => {
      dispatch({ type: CATEGORIES_GET_CATEGORIES, payload: data })
    })
  }
}

Reducer

const categories = (state = [], action) => {
  switch (action.type) {
    case CATEGORIES_GET_CATEGORIES:
      return action.payload
    default:
      return state
  }
}  

Component use

export default connect(state => ({ categories: state.categories }), {
  getCategories,
})(Category)

Upvotes: 2

Views: 55

Answers (1)

maioman
maioman

Reputation: 18734

Anytime from the moment you get the response you can select the categories array and pass that along,

in the comments I suggested to do that right after receiving the data object,

but you could also do it at the reducer phase or directly in the component.

Upvotes: 1

Related Questions