Reputation:
I have a react application that simply pull up a data from an api. Instead of api, i decided to use mongodb and created a simple db instead with express as a tool for server.
If I will use express alone I can simply do two things: 1. create a route where I can display all the data 2. create the ejs page where I can show all the data.
app.get('/cats', function(req, res){
cat.find({}, function(err, allCats){
if(err){
console.log(err);
} else {
res.render('cats', {cats: allCats});
}
})
});
And then from EJS file:
<% cats.forEach(cat => { %>
<h4><%= cat.title %></h4>
<h5><%= cat.breed %></h5>
<% }); %>
Now instead of throwing this data to ejs file/views I need to throw the data to my react app so it can handle the rendering for me:
class App extends Component{
constructor(props){
super(props);
this.state = {
cats: [],
};
this.catSearch('meow');
}
catSearch(term){
getCats(term, API_KEY, (cats) => {
this.setState({
cats: cats,
});
});
}
render(){
const catSearch = _.debounce((term) => { this.catSearch(term) }, 300);
return (
<div>
<SearchBar onSearchTermChange={catSearch}/>
<CatList cats={ this.state.cats }/>
</div>
);
}
};
Note: I've used a helper function here to pull up the api data however that's not the case here as I don't need to pull up the data from an api but instead I need to pull up the data from mongodb database.
Any idea how can I throw the data from express to my react file so it can handle the rendering?
Do i need to include some files to my react file so i can query the database? Thanks in advance. Been thinking about this for some time but no luck.
Upvotes: 1
Views: 2054
Reputation: 4333
In MERN, React requests are send to an express server which will query the database for the needed data. The data is then fetched by express and returned to React web app.
Create an express server which will fetch the name of all cats from MongoDB and return it to the ReactJS web app. You can use Mongoose to get data from MongoDB.
You have to have a componentDidMount()
method inside the class and put the api call inside it, to fetch the names. You have to then update the state (setState
) with the response received from the api.
Upvotes: 1