I have a problem: i want to show on the table just the "nameProcesso and "id" that has in the file json the attribute "errore = true".
I did the data fetch and now i can’t put the condition inside my function
Can someone help me?
import { useEffect, useState } from 'react';
import axios from 'axios';
export default function Fetch() {
'use client';
const [appState, setAppState] = useState([]);
useEffect(() => {
let Errore = false;
const fetchData = async () => {
const response = await axios.get(
'https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65'
);
const string = '[' + response.data + ']';
if (!Errore) {
setAppState(JSON.parse(string));
}
};
fetchData();
}, []);
const nameProcesso = (
<ul>
{appState.map((item) => {
switch(item){
case Errore || Errore.type === true:
return <p> {item.nameProcesso}</p>,<p> {item.id}</p>;
default:
return null;
}
}
)}
</ul>
);
return (
<table>
<thead>
<tr>
<th className={styles.colonnaErrori}>LISTA DEI PROCESSI IN ERRORE </th>
</tr>
</thead>
<tbody >
<tr className={styles.righeErrori}>
<td> {nameProcesso} </td>
</tr>
2
Answers
The variable Errore in your code is set to false and never updated. This makes the condition case Errore || Errore.type === true always evaluate to false.
I don’t think the switch statement is suitable for this kind of comparison, so, try an if statement instead.
Here’s a version that assumes that each item in your JSON data has a top-level "errore" attribute:
This version uses a Array.prototype.filter() method to create a new array that contains only the items where "errore" is true. Then, it maps over this new array to generate the list items.
attribute. This step should be performed before filtering or displaying the data.
You can adjust your useEffect and filteredItems
If you want to display only the items with the attribute "errore = true" in your table, you can an if condition within the .map() function. However, since you’re already using the .filter() method to create a filteredItems array, this isn’t strictly necessary for your specific use case. The filteredItems array should already contain only the items where "errore" is true, thanks to this line: