Search code examples
node.jsreactjsexpresscloudant

Fetch data from cloudant in react


I am new to nodejs. I want to create a visualization for the data that I have stored in cloudant.So, I have fetched data from cloudant in nodejs and I am not finding any way to send the data to react for visualization. I have fetched the cloudant data in nodejs console, now I don't understand how to send this data to react


Solution

  • Based on the description, assuming that you've built a REST api, in order for react to receive that data and map the data to views, you need to set up React project for the front end.

    In your app component, generally, the better way to do network call is by using ComponentDidMount lifecycle hook.

    You can use your preferred library to make network calls ex axios or fecth.

    Let us say you are fetching data about posts, the number of views, number of likes and number of dislikes etc. initialize them to empty objects.

    state = { 
    postLikes: 0,
    postDislikes: 0,
    comments: [],
    postViews: 0 
    }
    

    Now call the component did mount lifecycle hook to fetch the data

    async ComponentDidMount() {
     const data = await axios.get('http://yourApiEndpoint.com/resources');
     // you could also use fetch api .then() approach...
    
    // Now you need to update the state using setState method
     this.setState({postLikes: data.postLikes, postViews: data.postViews ... });
    }
    

    Once your state is updated react will re-render the parts of DOM which require rendering... The actual application will depend on the visualization library you are using... But if we were to display the above data as a text it is done as follows

    render(){
     return(
         <Fragment>
            <p>No. of likes: {this.state.postLikes} </p>
            <p>No. of dislikes: {this.state.postDislikes} </p>
              {/* and so on... render the stuff you need to render here */}
         </Fragment>
    );
    
    }
    

    This is a small example, The actual application depends on the data at hand and what you plan to do with it. I hope it has given you a brief idea.