0

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>
    )
}

4
  • 2
    That is an array! (See the square brackets surrounding it?) Try adding <p>notes[0].content</p>. As for the typeof, , in JavaScript arrays aren't actually a type, they are a class so an instance of an array is an object. Commented Feb 8, 2020 at 22:26
  • 1
    why do I not see anything. Maybe try Array#map instead of Array#forEach. Example: {notes.map(note => (<p>Test</p>)}. Render something if there are no notes, so you can distinguish between your own error and an empty application state. {(!notes || !notes.length) && (<p>No Notes here</p>)} Commented Feb 8, 2020 at 22:52
  • 1
    I think React expects you to use #map which will return an array of JSX expressions instead of iterating over your notes with #forEach Commented Feb 8, 2020 at 22:58
  • That was it, changing it to map fixed it, if you could update your answer to include that I will gladly accept it. :D Commented Feb 8, 2020 at 23:06

1 Answer 1

2

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

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.