Reputation: 101
I am trying to load data from a GET request into a table on my Next.js site. It works fine when I run it locally but when I publish it to a static site, it does not update the table each time.
I figured out that it pulls the data into a static HTML page when you export it to a static site but I want it to pull the data into the table each time. How do I ensure that it only populates the data with the data from the GET request and not the one on the static HTML page?
I am using the following code to perform the get request:
static getInitialProps = async function() {
var data;
await axios.get('https://myapi.com')
.then(res => {
data = res.data;
});
return {
items: data.TableData
}
}
I expect it to pull the data each time but it only pulls it on when I export it and it doesn't change thereafter.
Upvotes: 5
Views: 2731
Reputation: 112917
If you want to get the data at runtime, you can use the componentDidMount
life cycle hook and put it in the component state instead.
async componentDidMount() {
const res = await axios.get('https://myapi.com')
this.setState({ items: res.data });
}
Upvotes: 2