0

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!

1 Answer 1

1

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.

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.