rel1x
rel1x

Reputation: 2441

How to print normalized data in React/Redux

I have a data normalized using normalizr:

{
  result: "123",
  entities: {
    "articles": { 
      "123": { 
        id: "123",
        author: "1",
        title: "My awesome blog post",
        comments: [ "324" ]
      }
    },
    "users": {
      "1": { "id": "1", "name": "Paul" },
      "2": { "id": "2", "name": "Nicole" }
    },
    "comments": {
      "324": { id: "324", "commenter": "2" }
    }
  }
}

I save entities in reducer and I want to print them on my page. I can do that like this:

const articles = data.entities.articles;
for (let key in articles) {
  console.log( articles[key].author + ', ' +  articles[key].title);
}

Is that ok in React/Redux print normalized data in JSX template like this or there is exist a better way?

UPD

I create an application using this example https://github.com/reactjs/redux/tree/master/examples/real-world but I don't understand how there a data from entities printed in JSX templates.

I am confused about a data structure because usually I used arrays but in real-world example a new for me way, where data normalized like this.

Upvotes: 1

Views: 683

Answers (1)

Madura Pradeep
Madura Pradeep

Reputation: 2454

To connect your reducer with your view, you need a container. Then in your view, you can do something like in following jsfiddle.

https://jsfiddle.net/madura/g50ocwh2/

      var data = {
    result: "123",
    entities: {
      "articles": {
        "123": {
          id: "123",
          author: "1",
          title: "My awesome blog post",
          comments: ["324"]
        }
      },
      "users": {
        "1": {
          "id": "1",
          "name": "Paul"
        },
        "2": {
          "id": "2",
          "name": "Nicole"
        }
      },
      "comments": {
        "324": {
          id: "324",
          "commenter": "2"
        }
      }
    }
  };

  console.log(data.entities.articles);
  return ( < div > {
    Object.keys(data.entities.articles).map(function(key) {
      return <p key = {
        key
      } > {
        data.entities.articles[key].title
      } < /p>
    })
  } < /div>);
}

You will get your data as a property to your view after you connect with container. So you can access your data like below in your view.

this.props.data.entities.articles;

Upvotes: 1

Related Questions