im completly new to react. im made some simple app that received a string from backend.
the string looks like
"[{"name":"David", "age":"20"},{"name":"Michael", "age":"10"}]"
now i managed to make it into a string and render it the the website and i cant find the right way to make this string into a object and access it values to create a table that will show the different objects details.
i have found a function JSON.parse(obj)
but i guess I'm using it wrong.
I'm adding my code from App.js that atm rendering on the website.
function App() {
const [items, setItems] = useState([])
// Using useEffect for single rendering
useEffect(() => {
// Using fetch to fetch the api from
// flask server it will be redirected to proxy
fetch("/data")
.then((res) => res.json()
.then((data) => setItems(data))
);
}, []);
return (
<div className="App">
{items.map(item => {
return <pre>{JSON.stringify(item)}</pre>
})}
</div>
);
}
export default App;
You just simply need to do this:
return(
<table>
<thead>
<th>name</th>
<th>age</th>
</thead>
<tbody>
{items.map((item: any) => {
return (
<tr>
<td>{item.name}</td>
<td>{item.age}</td>
</tr>
)
})}
</tbody>
</table>
)
res.json() already converts your data to JSON, so you don't need to do anything extra. You are good to go to use your data.
in your .map() method item is the object which you need to use and access its property by simply doing item.propertyName as you can see in the code I shared.