av0000
av0000

Reputation: 1967

React/Redux - View treating array in store as object

I have an array at the root level of my Redux store but for some reason my view is treating it as an object.

Code Snippet:

const notes = useSelector(state => state.notes)
...
            <p>Notes</p>
            <p>{typeof notes}</p>
            <p>{JSON.stringify(notes)}</p>
            <p>{JSON.stringify(notes[0])}</p>

Is showing up as: enter image description here

I just want to make sure I'm not crazy and looking at the Redux docs it looks like this should be acceptable. Why might this not be working?

Edit

I'm glad I am not crazy, I guess my follow up question is why do I not see anything when I try:

export default function NotesTab() {
    const notes = useSelector(state => state.notes)
    return (
        <div className="flex flex-col w-full h-full justify-center items-center">
            {notes.forEach(note => (
                <p>Test</p>
            ))}
        </div>
    )
}

Upvotes: 0

Views: 97

Answers (1)

thor83
thor83

Reputation: 96

That's the expected behavior from typeof operator. It will report an array as an object. You can use Array.isArray() or Object.prototype.toString.call([]) which will give you [object Array]. Or Object.constructor.name.

> const foo = [1,2];
typeof foo; // object
< "object"

> Object.prototype.toString.call(foo)
< "[object Array]"

> foo.constructor.name
< "Array"

You can see from the output of JSON.stringify(notes) that your redux selector query is returning an array as you expected, so you should be good. HTH

Upvotes: 2

Related Questions