2

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)
3
  • 2
    instead of passing data have you tried to pass data.categories as payload? Commented Sep 27, 2017 at 16:44
  • I had not tried that, it worked! Could you write a short explanation why I needed to include that? Commented Sep 27, 2017 at 17:01
  • 1
    Because data is an object that has a key categories and the value for this key is the array you need. {key: value} is an object notation in JS. Commented Sep 27, 2017 at 18:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.