I'm using the next.js and i'm doing the fetch data fetch from json. Now i can't see the data from json (that change when i refresh) for example in the first box of the table.
Can someone help me? I just tried for so many days and i can't resolve.
import styles from '../styles2/Tabelle.module.css';
import { useEffect, useState } from 'react';
export default function Fetch() {
'use client';
const [appState, setAppState] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65');
const json = await response.json();
setAppState(json);
};
fetchData();
}, []);
const date = (
<ul>
{appState.map((item) => (
<li key={item.id}> {item.id} </li>
))}
</ul>
);
return (
<div>
<table>
<thead>
<tr>
<th>ID ESECUZIONE </th> <th>NOME PROCESSO</th> <th>HOST</th> <th>ANDAMENTO</th> <th>DURATA</th> <th>AVANZAMENTO</th>{' '}
</tr>
</thead>
<tbody>
<tr className={styles.righeEsecuzioni}>
<td> {date.key} </td>{' '}
</tr>
</tbody>
</table>
</div>
);
}
the response string does not contain array paranthesis [ ] in start and end thats why parsing JSON causing error
use axios library and you can do it like this
import library
import axios from 'axios';
fetch data
const response = await axios.get(
'https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65'
);
now add parenthesis at start and end
const string = '[' + response.data + ']';
now setState
setAppState(JSON.parse(string));
Overall code looks like this
import { useEffect, useState } from 'react';
import axios from 'axios';
export default function Fetch() {
'use client';
const [appState, setAppState] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await axios.get(
'https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65'
);
const string = '[' + response.data + ']';
setAppState(JSON.parse(string));
};
fetchData();
}, []);
const date = (
<ul>
{appState.map((item: any) => (
<li key={item.id}> {item.id} </li>
))}
</ul>
);
return (
<div>
<table>
<thead>
<tr>
<th>ID ESECUZIONE </th> <th>NOME PROCESSO</th> <th>HOST</th>{' '}
<th>ANDAMENTO</th> <th>DURATA</th> <th>AVANZAMENTO</th>{' '}
</tr>
</thead>
<tbody>
<tr>
<td> {date} </td>{' '}
</tr>
</tbody>
</table>
</div>
);
}
Sort by Date
Using dayjs library
Add this after string variable
const response = await axios.get(
'https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65'
);
const string = '[' + response.data + ']';
const parsedString = JSON.parse(string);
parsedString.sort((date1: any, date2: any) => {
return dayjs(date1.Giorno).isBefore(dayjs(date2.Giorno)) ? -1 : 1;
});
setAppState(parsedString);