admin管理员组

文章数量:1289603

I'm trying to update a piece of state with an array of data that I'm getting from the server. This is my reducer:

const schoolsDataReducer = (state = { data: [] }, action) =>
  produce(state, draft => {
    switch (action.type) {
      case SET_INITIAL__DATA:
        draft.data = [...action.payload.data]
        break
    }
  })

I get this error:

"Immer does not support setting non-numeric properties on arrays: data"

How am I supposed to store an array of objects?
Are arrays in the state considered bad practice?
Am I missing something?

I'm trying to update a piece of state with an array of data that I'm getting from the server. This is my reducer:

const schoolsDataReducer = (state = { data: [] }, action) =>
  produce(state, draft => {
    switch (action.type) {
      case SET_INITIAL__DATA:
        draft.data = [...action.payload.data]
        break
    }
  })

I get this error:

"Immer does not support setting non-numeric properties on arrays: data"

How am I supposed to store an array of objects?
Are arrays in the state considered bad practice?
Am I missing something?

Share Improve this question edited Oct 31, 2018 at 20:37 Dalton Cézane 3,7822 gold badges40 silver badges62 bronze badges asked Oct 31, 2018 at 20:21 Daniel ReinaDaniel Reina 6,3975 gold badges40 silver badges57 bronze badges 2
  • 2 Are you sure that state is actually an object at that point in time? Are you accidentally saving an array from a different action instead of an object with an array inside? – markerikson Commented Oct 31, 2018 at 20:23
  • You're right! I first tried to have the state as an array, instead of as an object with a data property being an array. That wasn't working so I updated the reducer but not the tests, so I was still sending an empty array as "previous state". Could you post an answer saying that I'm using an array? I guess people making the same mistake can e here and actually fix their code with your suggestion. – Daniel Reina Commented Oct 31, 2018 at 20:46
Add a ment  | 

1 Answer 1

Reset to default 9

This happens when you pass something not an object for state. Make sure state is an object.

本文标签: javascriptImmer does not support setting nonnumeric properties on arraysStack Overflow