Search code examples
reactjsreduxstore

Bracket notation while adding imported objects


In my redux store in an array I am storing several items, that I inject into store as exports.

To visualize, I've got separate file, where i store stuff like:

export const item1 = {
    name: 'item',
}

export const item2 = {
    name: 'item',
}

etc. Then I import this to reducer like this:

import * as items from './items';

And finally reducer looks like this:

stuff: [
    items.item1,
    items.item2
]

And now I want to create an action allowing me to add more objects into the reducer array that will be imported as objects from the file. Tried bracket notation like:

{
    ...state[0],
    stuff:[
        ...state[0].stuff,
        items['action.item']
    ]
},

But i get error "export 'action.item' (imported as 'items') was not found in './items'" so im out of ideas.

How can I do that? Action passes the new item name as string.


Solution

  • {
          ...state[0],
          stuff:[
             ...state[0].stuff,
             items[`${action.item}`]
          ]
    },
    

    As far as i understood , u are passing action.item as string. try the above approach. It should solve the issue.

    Note: if it's not intented mention full code for reducer file and also items.js file