Use Hooks to Format Table in Output

Use hooks to format table in output

I think other answers are from a time when the following didn't work, but now we can just do :

```{r results='asis', render=pander::pander}
head(x)
```

Or set this for all chunks in the setup chunk, for instance :

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, render=pander::pander)
```

Using React-Hooks/Axios to fetch data and display in a table

You are fetching data correctly, but setting data to state wrongly.

Also when you iterating your data array, you are printing table head each time which is wrong and from your data array address and company are object so you cant direct print the object.

You need to do this,

const App = () => {
const url = 'https://jsonplaceholder.typicode.com/users'

const [data, setData] = useState([])

useEffect(() => {
axios.get(url).then(json => setData(json.data))
}, [])

const renderTable = () => {
return data.map(user => {
return (
<tr>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.address.street}</td> //only street name shown, if you need to show complete address then you need to iterate over `user.address` object
<td>{user.company.name}</td> //only company name shown, if you need to show complete company name then you need to iterate over `user.name` object
</tr>
)
})
}

return (
<div>
<h1 id="title">API Table</h1>
<table id="users"> //Your Table in post changed to table to make it work
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Company</th>
</tr>
</thead>
<tbody>{renderTable()}</tbody>
</table>
</div>
)
}

Demo

How to initialize data using map inside useState in ReactJs?

If props.comments is a populated array on the initial render cycle then mapping it in the useState hook for the initial state value should work. If it is not available on the initial render then you'll use an useEffect hook with a dependency on props.comments to update the rowData state when it [comments] updates.

const { comments } = props;

const [rowData, setRowData] = useState([]);

useEffect(() => {
setRowData(comments.map(comment => ({
postName: comment.inputs.postName,
commentName: comment.name,
size: getSize(comment)
})));
}, [comments]);

Get my arrow function output and display it in a table format in render component in React

You should keep your data in your state then render it into the DOM.

const data = {  ResponseMetadata: { RequestId: "12345" },  MetricDataResults: [    {      Id: "m17",      Label: "StandardStorage BucketSizeBytes",      Timestamps: ["2018-09-04T18:30:00.000Z"],      Values: [38497162],      StatusCode: "Complete",      Messages: []    },    {      Id: "m18",      Label: "AllStorageTypes NumberOfObjects",      Timestamps: ["2018-09-04T18:30:00.000Z"],      Values: [10],      StatusCode: "Complete",      Messages: []    }  ]};
const fakeRequest = () => new Promise(resolve => setTimeout(() => resolve(data)));
class App extends React.Component { state = { data: {} };
handleClick = () => fakeRequest().then(data=> this.setState({ data }));
renderResults = () => this.state.data.MetricDataResults.map(MetricDataResults => ( <div key={MetricDataResults.Id}> <p>ID: {MetricDataResults.Id}</p> <p>Label: {MetricDataResults.Label}</p> <p>Timestamp: {MetricDataResults.Timestamps}</p> <p>Values: {MetricDataResults.Values}</p> <p>StatusCode: {MetricDataResults.StatusCode}</p> <p>Messages: {MetricDataResults.Messages}</p> </div> ));
render() { return ( <div> {this.state.data.MetricDataResults && this.renderResults()} <button onClick={this.handleClick}>Get results</button> </div> ); }}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>

React Table w/JSON API hooks?

Your code is fine except for a few modifications. You can find the final code here

  1. How/Where do people normally set/store the column data and "data"
    data when using react table. I'd assume just a const for the
    columns....but where is the data stored? (I'd normally store it in
    state in a class, but since im trying to use hooks I am unsure)

    Answer

    • It is based on the application requirement.
    • If the data needs to be persisted in the client-side and shared across several modules/components then use redux to store your data.
    • If the data is required (not to be kept for the long run) only when the user visits the screen, then keep the data in the component state.
  2. I feel like my useEffect() is wrong for fetching API data. I also ran into a bug where it constantly kept running. I saw someone suggest to check the length to prevent this....but this feels hacky. What's the correct way to do this?

    Answer:

    • As per your code, there is no requirement/need to pass dependencies in useEffect hook. (This happens because you are trying to maintain the same data in two-component state i.e data and sensors. but there is no need- PS see the attached code in the above link. Have a look at Conditionally filtering an effect
    • If you want to run an effect on mount only once (componentDidMount), you can pass an empty array ([]) as a second argument. So it never re-runs.
  3. I can't quite figure out how to map the data how I want to with React.useMemo I can't find any examples either (Apparently react table requires this). Any Advice?

    Answer:

    • What do you mean by how to map the data?. Want to do some transformation on the response object from API ?. If yes you can use any Javascript built-in methods or you can use 3rd party library like ramda or lodash
    • useMemo is not required in your case as You're not doing any complex operation and your data source is API.
    • Some note mentioned in reactjs documentaion regarding useMemohook

Remember that the function passed to useMemo runs during rendering.
Don’t do anything there that you wouldn’t normally do while rendering.
For example, side effects belong in useEffect, not useMemo.

Your code is fine and there are no issues, except maintaining the same data in two separate component state variables.

Refer to the lines marked with <---- in below code

  // const [sensors, setSensors] = useState([]); No need to maintain same data in two state variables
const [data, setData] = useState([])

useEffect(() => {
// GET sensor list from API
axios
.get("http://localhost:3000/api/v1/devices.json")
// .then((response) => {
// handle success
// console.log(response);
// setSensors(response.data.data)
// }) <------- this is not required
.then((response) => {
// ......
const data = response.data.data.map(sensor =>
({
id: sensor.id,
name: sensor.name,
serialNum: sensor.serialNumber,
status: sensor.deviceStatus
})
)
setData(data)
})
.catch((error) => {
console.log(error);
})
// }, [sensors.length]);
}, []); // <--------- like componentDidMount in classBased components

Added final code in working codesandbox here

access the data of a hook- React

You need to check if the results property is defined.

<div className="App">
<h1>Total {Data.total_results}</h1>
{typeof Data.results !== "undefined" &&
Data.results.map((movie, index) => {
return <h3>{movie.title}</h3>;
})}
</div>

Working Demo: https://codesandbox.io/s/distracted-feather-4l55r

A few days back, I have created a repository and implemented OMDB API with React. This may help you.

https://github.com/jogeshpi03/omdb-react



Related Topics



Leave a reply



Submit