0

Quite new to React on Rails apps, especially the React portion. I'm trying to access data in a nested hash that is given from a SQL query in a Rails service. First off, is this even possible?

In Rails Console, lets say user1 has already been found by id, LedgersService.transactions(user1).first returns all data in this format:

{:transactable=>{:type=>"Deposit", :id=>"28cba04f-5b9d-4c9c-afca-b09a6e0e8739", :user_id=>"72700244-e6b0-4baf-a381-c22bfe56b022", :transacted_at=>"2019-03-12 19:04:48.715678", :amount_cents=>15, :notes=>"none", :processor=>nil, :details=>nil}, :ledgers=>[{:entry_type=>"credit", :amount_cents=>15, :transacted_at=>"2019-03-12 19:04:48.715678", :user_id=>"72700244-e6b0-4baf-a381-c22bfe56b022", :transactable_type=>"Deposit", :transactable_id=>"28cba04f-5b9d-4c9c-afca-b09a6e0e8739"}]}

I am attempting to do something similar in my React component to try to get the data, however, I'm not quite sure how to set LedgersService.transactions portion. This is how I currently have it:

class LedgersIndex extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ledgers_service: { transactions: [] }, paginator: { count: 0, page: 0, limit: 0 }, user: { id: this.props.match.params.user_id } };

My endpoint call:

componentDidMount() {
    var user_id = this.state.user.id;
    this.fetchData(user_id, 1);
  }

  fetchData = (user_id, page_number) => {
    apiService.ledgersIndex(user_id, page_number)
      .then(
        paginated => {
          this.setState({
            ledgers_service: { 
              transactions: paginated.ledgers_service.transactions
            },
            paginator: {
              limit: paginated.meta.limit,
              count: paginated.meta.count,
              page: paginated.meta.page -1
            }
          });
        },

Further down in my render:

render() {
    const { classes } = this.props;
    const { ledgers_service, paginator } = this.state;

My fetch in apiService:

function locationsIndex(page_number) {
  const requestOptions = {
    method: 'GET',
    headers: Object.assign({},
      authorizationHeader(),
      {  'Content-Type': 'application/json' })
  };

  return fetch(`${process.env.API_SERVER}/api/v1/admin/locations?page=${page_number}`, requestOptions)
    .then(handleResponse)
    .then(paginated => {
      return paginated;
    });
}

When I console.log(ledgers_service.transactions(this.state.user.id)), I get the error that ledgers_service.transactions is not a function. console.log(paginator.count) however worked, is this because transactions is being set to an array?

What's the correct way to get that same endpoint in my React component that I got from my rails console?

Sachin
  • 27
  • 5

1 Answers1

0

Quite new to React on Rails apps, especially the React portion. I'm trying to access data in a nested hash that is given from a SQL query in a Rails service.

Yes, JS likes JSON so you should have a Rails action that responds with JSON. This is the correct way to exchange data between React and Rails:

# in your React app
fetch('/path/to/resource.json')
.then((returnedResource) => {
      // do something with JSON
 })
.catch(error => console.error('Error:', error));

# in your controller
respond_to do |format|
     format.json { render json: LedgersService.transactions(user1).first }
end

From there, you can treat your returnedResource as a JSON object. In your case, this would be pagination

Veridian Dynamics
  • 1,405
  • 1
  • 9
  • 19
  • This is how the controller is currently, in my User class: ** def transactions t = LedgersService.transactions(@user) json_response(t) end ** Will the first at the end still render all of the responses 1 by 1? – Sachin Mar 21 '19 at 16:19
  • I updated my fetch in my original question at the bottom. And the main thing I want returned that isn't is the data from LedgersService, how exactly is that accessible in React? I've tried what's included above, setting ledgers_service: [], in this.state, then I also tried just transactions: [] in state, all returning empty – Sachin Mar 21 '19 at 16:22
  • I do not understand your last question. Don't try to fit too much code in these comments because they are hard to read. Edit your post when including more relevant details. If you want to show things 1-by-1, there are hundreds of ways to do that and I can't possibly enumerate them all. If you can get your data from Rails in a JSON format, then this thread is dead and I've successfully answered your original question. If you need further assistance, please move this conversation to a chat with me or a place like https://reddit.com/r/learnprogramming/new. I'll look for your post. – Veridian Dynamics Mar 21 '19 at 16:26