cshermans
cshermans

Reputation: 105

How to iterate over json object in React js

Nodejs total noob here.

Trying to post a Mongoose DB query through json from an express server to a REACT app, currently achieving this via a .get shown below.


app.get('/posty', (req,res) => {
   if (req.session.user && req.cookies.user_id) {

   Blog.find({name : "my_user"}).exec(function(err, blogs) {   
      if (err) throw err;
      res.json([
         {name : req.session.user.name, text : blogs},
      ]);
   })
   } else {
      res.redirect('/login');
   }
});

My react App.js looks like this

import logo from './logo.svg';
import './App.css';
import Texts from './components/texts/texts';
import React, { Component } from 'react';

class App extends Component {
  state = { posty: []}
  
  componentDidMount() {
    fetch('/posty')
      .then(res => res.json())
      .then(posty => this.setState({posty}));
  }

  render() {
    return (
    
      <div className="App">
        <header className="App-header">
          <Texts>  </Texts>
          <ul> 
            { 
            this.state.posty.map(post => 
              <li key={post.name}>{post.text[0].content } </li>
            )}
            </ul>
        </header>
      </div>
    );
  }
}

export default App;

This achieves what you'd expect, the outputs the Blogs array at index 0.

What I'm trying to achieve is an array that iterates over the Blog json data, and outputs ALL .contents, not just for Blog[0].

This may seem like a simple question but I am a total NodeJS noob! I apologize!

If you have any general advice other than this I am all ears, thank you!

Upvotes: 0

Views: 316

Answers (1)

Ankit Aabad
Ankit Aabad

Reputation: 155

first thing instead of sending an array in res.json you should just send the object:

instead of

res.json([
     {name : req.session.user.name, text : blogs},
  ])

just send

res.json({name : req.session.user.name, text : blogs})

now in react: instead of

componentDidMount() {
    fetch('/posty')
      .then(res => res.json())
      .then(posty => this.setState({posty}));
  }

write this

componentDidMount() {
    fetch('/posty')
      .then(res => res.json())
      .then(posty => this.setState({posty: posty.text}));
  }

finally instead of

<li key={post.name}>{post.text[0].content } </li>

do this

<li key={post.name}>{post.content } </li>

I'm assuming the blogs contains the name as well as the content.

In case you want that req.session.user.name, you should use another state variable for that.

Upvotes: 1

Related Questions