'React: Fetching inside a map and modifying a useState array
Can you guys please help me with a basic React app :) I want to read a json file:
[
{
"name": "Google",
"url": "www.google.com",
"status": "to evaluate"
},
{
"name": "Bing",
"url": "www.bing.com",
"status": "to evaluate"
},
etc.
]
While reading it, I want to fetch the url to fill the status in this json file
finally, I just want to make a table that has two columns: the first is the name with the url, the second is the status
I tried this but it does not work :O
import React, { useState } from 'react'
import Table from 'react-bootstrap/Table'
import jsonData from './data/urls.json'
function ListUrls () {
const [jsonArray, setJsonArray] = useState(jsonData)
async function fetchData (array) {
try {
array.map (url => {
const response = await fetch(url.url)
setJsonArray(url.status = response.status)
})
} catch (error) {
console.log('Error', error);
}
fetchData(jsonArray)
return (
<div>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{jsonArray.map(url => (
<tr>
<td>
<a href={url.url} target='_blank'}>
{url.name}
</a>
</td>
<td>
{url.status}
</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
export default ListUrls
Btw, I would really want to use hooks to do it :)
So, I would except to see this table, but the page is blank :/
Solution 1:[1]
You should change jsonArray to jsonData as the parameter and set the initial state to be null.
Currently you are passing in the state (jsonArray) instead of jsonData when calling the function. Also you should put the call to fetchData in a useEffect with jsonData as the parameter:
useEffect(() => fetchData(jsonData), [jsonData, fetchData]);
Solution 2:[2]
Would this become a loop? Component loads -> fetchData() is called -> fetchData() updates the state -> Component reloads -> repeat.
You could use a useEffect() hook with an empty array as the second argument to only run once:
useEffect(() => {
//Update json as you were doing;
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lucas Claude |
| Solution 2 | net00 |

