0

I'm trying to figure out how to code my current API call so that I can access each field from the API call and render it, then be able to use it across multiple components. I'm using the QuickBase API call that only allows POST to pull field values. I've been out of the game for a couple of years and can't figure out how to accurately render these to be able to be used in other components by importing the api.js file. The project is a React within Electron to pull QuickBase data, and be able to create Line Charts (7 on one page) to show a job cost/hours and the jobs included departments cost/hours. All of my data is in quickbase, I just can't figure out how to get it over to react and able to actually use it!

Here is my API call:

let headers = {
  'QB-Realm-Hostname': 'XXXXXXXXX.quickbase.com',
  'User-Agent': 'FileService_Integration_V2.1',
  'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXX',
  'Content-Type': 'application/json'
}
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}

fetch('https://api.quickbase.com/v1/records/query',
  {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(body)
  })
  
.then(res => {
  if (res.ok) {
    return res.json().then(res => console.log(res));
  }

return res.json().then(resBody => Promise.reject({status: res.status, ...resBody}));
})

.catch(err => console.log(err))

Any help would be greatly appreciated as I've been struggling on this for awhile! Right now I'm able to get all the correct data in the Console. But don't know how to go about rendering it on my application for actual use.

Thanks!

Alex
  • 131
  • 9

2 Answers2

0

I think you should put your code inside a function and call that function from the component where you need the data, something like

import React, { Component } from 'react'

let headers = {
  'QB-Realm-Hostname': 'XXXXXXXXX.quickbase.com',
  'User-Agent': 'FileService_Integration_V2.1',
  'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXX',
  'Content-Type': 'application/json'
};

class App extends Component {
  state = {
    data: null,
  }

  componentDidMount() {
    this.fetchData();
  }    

  fetchData = () => {    
    let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}

    fetch('https://api.quickbase.com/v1/records/query', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(body)
    }).then(response => {
      if (response.ok) {
        return response.json().then(res => {
          this.setState({
            data: res,
          })
        });
      }

      return response.json().then(resBody => Promise.reject({status: response.status, ...resBody}));
    }).catch(err => console.log(err))
  }

  render() {
    const { data } = this.state;

    if (data === null) return 'Loading...';

    return (
      <div>
        {/* Do something with data */}
      </div>
    );
  }
}

export default App;
  • Is it good practice to have multiple calls for each component? Or could this be changed to have one file with the call and sets the data, then I can call that file and reference the data in my components? – Alex Apr 23 '21 at 17:26
  • This was an example. The best practice probably would be to have all your api calls in a single file and import them in the components where you need them. In that case you can return the fetch and manage the promise (.then and .catch) on the component where you make the call – Jesús Domínguez Apr 23 '21 at 17:31
  • Can I ask, if I did it this way, I would be able to select each/ any of the selected field numbers in the body as needed? this is where I'm getting confused on how I can say, ok let me take 6 and use that value in a different component... – Alex Apr 23 '21 at 17:43
  • Not sure if i understand the question. But for example, the `body` or part of it, can be passed to the function as parameter, so each component can make different requests with different bodies. – Jesús Domínguez Apr 23 '21 at 17:51
  • Hey Jesus, I'm still unable to get anything to render, no errors, but nothing displays. in the dive i'm calling {data} – Alex Apr 26 '21 at 19:32
  • how does `data` looks? is probably an object (so you have to access the attributes like `dafa.foo` or `data.bar`) or an array (you have to iterate it `data.map((value) => (
    {value}
    ))`) (value might be an object so just refer to the first example)
    – Jesús Domínguez Apr 27 '21 at 06:18
  • here is what my data is looking like in the console. – Alex Apr 27 '21 at 14:19
  • ```{data: Array(200), fields: Array(44), metadata: {…}} data: Array(200) [0 … 99] 0: {3: {…}, 18: {…}, 20: {…}, 144: {…}, 145: {…}, 171: {…}, 172: {…}, 174: {…}, 212: {…}, 215: {…}, 216: {…}, 217: {…}, 218: {…}, 219: {…}, 220: {…}, 221: {…}, 222: {…}, 223: {…}, 227: {…}, 230: {…}, 231: {…}, 232: {…}, 233: {…}, 234: {…}, 235: {…}, 236: {…}, 244: {…}, 249: {…}, 322: {…}, 325: {…}, 338: {…}, 349: {…}, 350: {…}, 351: {…}, 366: {…}, 438: {…}, 513: {…}, 516: {…}, 517: {…}}``` – Alex Apr 27 '21 at 14:21
  • Well, just follow that structure to show what you need. – Jesús Domínguez Apr 28 '21 at 10:15
0

Check the Docs, you can send the JSON in the props of the component to render it. You can modify your code following this example.

sandbox

import { useEffect, useState } from "react";

async function apiCall() {
  return await new Promise((resolve, reject) => {
    // Api Call
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => resolve(json));
  });
}
const TestApp = () => {
  let [data, setData] = useState({ Text: "Before api call." });

  useEffect(() => {
    (async () => {
      let res = await apiCall();
      res.Text = "After api call.";
      setData(res);
    })();
  }, []);
  return (
    <div>
      UserId: {data.userId} &nbsp; id: {data.id} &nbsp; title: {data.title}{" "}
      &nbsp; completed: {data.completed}
    </div>
  );
};

module.exports = TestApp;

Prithvi Singh
  • 50
  • 1
  • 5
  • I'm getting an error with the following code, ``` ({ data }: Props) ``` Props is undefined Also had to change it to ({ data } = Props), because the syntax before was saying that could only be used with .ts or .tsx – Alex Apr 26 '21 at 16:42
  • Updated the code, should work now. And checkout sandbox too. – Prithvi Singh Apr 27 '21 at 16:44