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
"crates": [{
"id": 1,
"nameCrate": "Pauls crate",
"albums": ["Blue Bossa", "Boogarins"]
},
{
"id": 2,
"nameCrate": "Lauras crate",
"albums": ["ABBA", "Blof"]
}
]
}
index.tsx
import { useState, useEffect } from 'react'
export default function Home() {
interface Crate {
id: string;
nameCrate: string;
albums: string;
}
const [crates, setCrates] = useState<Array<Crate>>([]);
useEffect(() => {
fetch('data.json',{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((res) => res.json())
.then((resJson) => {const data = JSON.stringify(resJson)
setCrates(data.data)})
}, [])
console.log(crates)
return (
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
Main
{crates && crates.map((crate) => (<div key={crate.id} {...crates}>{crate.nameCrate}</div>))}
</main>
<footer className="bg-black">
<div>This is the footer </div>
</footer>
</div>
)
}
CodePudding user response:
No need to stringify since response is json
{
const data = resJson.crates
setCrates(data)// set crates
})