I am trying to get the names displayed of a ‘Crate’ (a crate full of records/albums), derived from a local JSON file. But it’s not showing up. Should I be using params? Should I have not stringified the JSON? VSC tells me Property ‘data’ does not exist on type String. Before this I received an error that crates.map is not a function, indicating that the JSON was an object not an array.
public/data.json
JavaScript
x
13
13
1
"crates": [{
2
"id": 1,
3
"nameCrate": "Pauls crate",
4
"albums": ["Blue Bossa", "Boogarins"]
5
},
6
{
7
"id": 2,
8
"nameCrate": "Lauras crate",
9
"albums": ["ABBA", "Blof"]
10
}
11
]
12
}
13
index.tsx
JavaScript
1
49
49
1
import { useState, useEffect } from 'react'
2
3
export default function Home() {
4
5
interface Crate {
6
id: string;
7
nameCrate: string;
8
albums: string;
9
}
10
11
const [crates, setCrates] = useState<Array<Crate>>([]);
12
13
useEffect(() => {
14
fetch('data.json',{
15
headers : {
16
'Content-Type': 'application/json',
17
'Accept': 'application/json'
18
}
19
})
20
.then((res) => res.json())
21
.then((resJson) => {const data = JSON.stringify(resJson)
22
setCrates(data.data)})
23
}, [])
24
25
console.log(crates)
26
27
28
29
return (
30
<div>
31
<Head>
32
<title>Create Next App</title>
33
<meta name="description" content="Generated by create next app" />
34
<link rel="icon" href="/favicon.ico" />
35
</Head>
36
37
<main>
38
Main
39
{crates && crates.map((crate) => (<div key={crate.id} {crates}>{crate.nameCrate}</div>))}
40
41
</main>
42
43
<footer className="bg-black">
44
<div>This is the footer </div>
45
</footer>
46
</div>
47
)
48
}
49
Advertisement
Answer
No need to stringify since response is json
JavaScript
1
5
1
{
2
const data = resJson.crates
3
setCrates(data)// set crates
4
})
5